标签:
1 #include<stdio.h> 2 #include <string.h> 3 #include<math.h> 4 #define Min(x,y) (x<y?x:y) 5 const int INF=0x3f3f3f3f; 6 const int MAXN=610; 7 bool prim[1000010]; 8 int N,answer; 9 int judge(int a,int b){ 10 if(!prim[a]||!prim[b]||!prim[a+b]){ 11 return Min(Min(a,b),fabs(a-b)); 12 } 13 else return -1; 14 } 15 void pt(){ 16 memset(prim,false,sizeof(prim)); 17 prim[0]=prim[1]=true; 18 for(int i=2;i<=1000;i++){ 19 if(!prim[i])for(int j=i*i;j<1000010;j+=i){ 20 prim[j]=true; 21 } 22 } 23 } 24 int map[MAXN][MAXN],vis[MAXN],low[MAXN]; 25 int v[MAXN]; 26 void prime(){ 27 int k; 28 int temp,flot=1; 29 answer=0; 30 memset(vis,0,sizeof(vis)); 31 vis[0]=1; 32 for(int i=0;i<N;i++)low[i]=map[0][i]; 33 for(int i=0;i<N;i++){ 34 temp=INF; 35 for(int j=0;j<N;j++) 36 if(!vis[j]&&temp>low[j]) 37 temp=low[k=j]; 38 if(temp==INF){ 39 if(flot==N)printf("%d\n",answer); 40 else puts("-1"); 41 break; 42 } 43 answer+=temp; 44 vis[k]=1; 45 flot++; 46 for(int j=0;j<N;j++) 47 if(!vis[j]&&low[j]>map[k][j]) 48 low[j]=map[k][j]; 49 } 50 } 51 int main(){ 52 int T,t; 53 scanf("%d",&T); 54 while(T--){ 55 pt(); 56 memset(map,INF,sizeof(map)); 57 scanf("%d",&N); 58 for(int i=0;i<N;i++)scanf("%d",&v[i]); 59 for(int i=0;i<N;i++) 60 for(int j=i+1;j<N;j++){ 61 t=judge(v[i],v[j]); 62 if(t>=0){ 63 if(t<map[i][j])map[i][j]=map[j][i]=t; 64 } 65 } 66 prime(); 67 } 68 return 0; 69 }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4725330.html