View Code
1 #include<stdio.h> 2 #include<math.h> 3 #include<string.h> 4 #define M 999999999 5 #define N 2000000 6 int a[610],map[610][610]; 7 int b[610],c[610],g[N]; 8 int Min(int x,int y) 9 { 10 if(x>y) 11 return y; 12 else 13 return x; 14 } 15 void prim() 16 { 17 int i,j; 18 int flag=1; 19 memset(g,0,sizeof(g)); 20 g[0]=1;g[1]=1; 21 for(i=2;i<=N;i++) 22 { 23 if(!g[i]) 24 { 25 for(j=i+i;j<=N;j+=i) 26 g[j]=1; 27 } 28 } 29 } 30 int fun(int x,int y) 31 { 32 if(!g[x]||!g[y]||!g[x+y]) 33 return 1; 34 else 35 return 0; 36 } 37 int main() 38 { 39 int tt,n,i,j,x,y; 40 scanf("%d",&tt); 41 42 prim(); 43 while(tt--) 44 { 45 scanf("%d",&n); 46 for(i=1;i<=n;i++) 47 scanf("%d",&a[i]); 48 memset(map,0,sizeof(map)); 49 memset(b,0,sizeof(b)); 50 51 for(i=1;i<=n;i++) 52 { 53 for(j=i+1;j<=n;j++) 54 { 55 map[i][j]=map[j][i]=M; 56 if(fun(a[i],a[j])) 57 { 58 x=Min(a[i],a[j]); 59 if(a[i]>a[j]) 60 y=a[i]-a[j]; 61 else 62 y=a[j]-a[i]; 63 64 map[i][j]=map[j][i]=Min(x,y); 65 } 66 } 67 } 68 c[1]=0; 69 for(i=2;i<=n;i++) 70 c[i]=map[1][i]; 71 int t,flag=0; 72 t=1; 73 c[t]=0; 74 int sum=0; 75 while(b[t]==0) 76 { 77 b[t]=1; 78 for(i=1;i<=n;i++) 79 if(b[i]==0&&c[i]>map[t][i]) 80 c[i]=map[t][i]; 81 int min=M; 82 for(i=1;i<=n;i++) 83 if(b[i]==0&&min>c[i]) 84 { 85 min=c[i]; 86 t=i; 87 } 88 if(min!=M) 89 { 90 sum+=min; 91 } 92 93 } 94 for(i=1;i<=n;i++) 95 { 96 if(c[i]>=M) 97 { 98 flag=1; 99 break; 100 } 101 } 102 if(flag==0) 103 printf("%d\n",sum); 104 else 105 printf("-1\n"); 106 } 107 return 0; 108 }