hdu 2682 Tree 最小生成树 (并查集)
2015-03-26 17:43
302 查看
Tree
Time Limit : 6000/2000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 26 Accepted Submission(s) : 10
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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 toconnecte two cities is Min(Min(VA , VB),|VA-VB|).
Now we want to connecte all the cities together,and make the cost minimal.
Input
The first will contain a integer t,followed by t cases.Each case begin with a integer N,then N integer Vi(0<=Vi<=1000000).
Output
If 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
Author
Teddy最小生成树:类似于畅通工程一类的,不过中间多加了素数的处理判断
#include<stdio.h> #include<iostream> #include<string.h> #include<algorithm> using namespace std; struct inin { int a; int b; int dis; }boy[410000]; int p[660]; int prime[1000010]; int p2[660]; int cmp(inin a,inin b) { return a.dis<b.dis; } int find(int n) { return p ==n ? n : p = find(p ); } int main() { int T; int n; int k; int re; int sum; int i,j; prime[0]=1; prime[1]=1; prime[2]=0; for(i=2;i<1000000;i++) { if(!prime[i]) { for(j=i*2;j<1000000;j+=i) { prime[j]=1; } } } scanf("%d",&T); while(T--) { scanf("%d",&n); memset(p2,0,sizeof(p2)); memset(boy,0,sizeof(boy)); for(i=0;i<=n;i++) { p[i]=i; } for(i=1;i<=n;i++) { scanf("%d",&p2[i]); } k=0; for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { int temp=p2[i]-p2[j]; if(temp<0) temp=-temp; // if(i!=j) if(!prime[p2[i]]||!prime[p2[j]]||!prime[p2[i]+p2[j]]) { boy[k].a=i; boy[k].b=j; boy[k++].dis=min(p2[i],min(p2[j],temp)); } } } sort(boy,boy+k,cmp); sum=0; re=1; for(i=0;i<k;i++) { int f1=find(boy[i].a); int f2=find(boy[i].b); if(f1!=f2) { sum+=boy[i].dis; p[f1]=f2; re++; } } if(re!=n) { printf("-1\n"); } else { printf("%d\n",sum); } } return 0; }
相关文章推荐
- HDU-1863(最小生成树+并查集判断是否连通)
- HDU 1863 并查集+最小生成树
- 【最小生成树】+【并查集】-HDU-1233-还是畅通工程
- hdu 1879_并查集_最小生成树_Kruskal
- HDU 1598 find the most comfortable road 【枚举+(并查集)最小生成树Kruskal】
- 【解题报告】 HDU 1102 Constructing Roads -- 并查集 最小生成树 Prime算法
- hdu 1102 (最小生成树kruskal算法--并查集,prim死活过不了)
- 【最小生成树】+【并查集】-HDU-1879-继续畅通工程
- HDU 1233(最小生成树,并查集)
- hdu 1232 畅通工程 并查集 最小生成树
- HDU 4463 最小生成树 并查集
- HDU-4750 Count The Pairs 最小生成树,并查集
- hdu 1233 还是畅通工程 Kruskal 最小生成树 并查集
- HDU 1233 (最小生成树) 用并查集实现kruskal
- HDU-1301 Jungle Roads 并查集/最小生成数
- HDU 3367 Pseudoforest (最小生成树,并查集)
- [HDU] 3371 Connect the Cities [最小生成树,并查集,Kruskal]
- hdu 1233 还是畅通工程 Kruskal 最小生成树 并查集
- hdu-1863畅通工程 最小生成树克鲁斯卡尔算法kruskal(并查集实现)&&prim普利姆算法实现
- HDU 3371 Connect the Cities (最小生成树 并查集+克鲁斯卡尔)