HDU - 2682 Tree

There are N (2<=N<=600) cities,each has a value of happiness,we consider two cities A and B whose value of happiness are VA and VB,if VA is a prime number,or VB is a prime number or (VA+VB) is a prime number,then they can be connected.What's more,the cost to connecte two cities is Min(Min(VA , VB),|VA-VB|).
Now we want to connecte all the cities together,and make the cost minimal.InputThe first will contain a integer t,followed by t cases.
Each case begin with a integer N,then N integer Vi(0<=Vi<=1000000).OutputIf the all cities can be connected together,output the minimal cost,otherwise output "-1";Sample Input

2
5
1
2
3
4
5

4
4
4
4
4

Sample Output

4
-1
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 
 7 using namespace std;
 8 
 9 int f[605],z[605],prime[1000005],M=1000000;
10 struct node
11 {
12     int u,v,w;
13     friend bool operator <(node x,node y)
14     {
15         return x.w<y.w;
16     } 
17 }G[400005];
18 
19 int find(int x)
20 {
21     if(x!=f[x])
22         return find(f[x]);
23     return x;
24 }
25 
26 void dabiao()
27 {
28     int i,j;
29     memset(prime,0,sizeof(prime));//素数为0 
30     for(i=2;i<M;i++)
31     {
32         if(!prime[i])
33         {
34             for(j=2*i;j<M;j+=i)
35             {
36                 prime[j]=1;
37             }    
38         }
39     }
40     prime[1]=1;
41 }
42 
43 int main()
44 {
45     int n,m,T;
46     scanf("%d",&T);
47     dabiao();
48     while(T--)
49     {
50         scanf("%d",&n);
51         m=0;
52         memset(G,0,sizeof(G));
53         memset(z,0,sizeof(z));
54         for(int i=0;i<n;i++)
55             f[i]=i;
56         for(int i=0;i<n;i++)
57             scanf("%d",&z[i]);
58         for(int i=0;i<n;i++)
59             for(int j=i+1;j<n;j++)
60             {
61                 if(prime[z[i]]==1&&prime[z[j]]==1&&prime[z[i]+z[j]]==1)
62                     continue;
63                 G[m].u=i;
64                 G[m].v=j;
65                 G[m++].w=min(min(z[i],z[j]),abs(z[i]-z[j]));
66                 //cout<<G[m-1].u<<" "<<G[m-1].v<<endl;
67             }
68         sort(G,G+m);
69         long long ans=0;
70         int s=0;
71         //cout<<"m  "<<m<<endl;
72         for(int i=0;i<m;i++)
73         {
74             int f1=find(G[i].u);
75             int f2=find(G[i].v);
76             if(f1!=f2)
77             {
78                 f[f2]=f1;
79                 ans+=G[i].w;
80                 s++;
81             }
82             if(s==n-1)
83                 break;
84         }
85         if(s<n-1)
86             printf("-1\n");
87             else
88                 printf("%lld\n",ans);
89     }
90 }

 

posted @ 2017-08-10 17:44  西北会法语  阅读(146)  评论(0编辑  收藏  举报