Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6506 Accepted Submission(s): 2983
最小生成树问题,不在多讲,直接写模板(Kruskals)
代码:
1 #include<stdio.h>
2 #include<queue>
3 using namespace std;
4 int father[105],rank[105];
5 typedef struct node
6 {
7 int x,y;
8 int s;
9 bool operator<(const node &a)const
10 {
11 return a.s<s;
12 }
13 }NODE;
14 int find(int x)
15 {
16 if(x!=father[x])
17 {
18 father[x]=find(father[x]);
19 }
20 return father[x];
21 }
22 void Union(int x,int y)
23 {
24 if(rank[x]>rank[y])
25 {
26 father[y]=x;
27 }
28 else
29 {
30 if(rank[x]==rank[y])
31 {
32 rank[y]++;
33 }
34 father[x]=y;
35 }
36 }
37 int main()
38 {
39 NODE cur;
40 priority_queue<NODE> qu;
41 int n,t,i,x,y,s,sum;
42 while(scanf("%d",&n)!=EOF)
43 {
44 sum=0;
45 if(n==0)
46 break;
47 t=n*(n-1)/2;
48 for(i=1;i<=n;i++)
49 {
50 father[i]=i;
51 rank[i]=0;
52 }
53 for(i=1;i<=t;i++)
54 {
55 scanf("%d%d%d",&x,&y,&s);
56 cur.x=x;
57 cur.y=y;
58 cur.s=s;
59 qu.push(cur);
60 }
61 while(!qu.empty ())
62 {
63 cur=qu.top ();
64 qu.pop();
65 x=cur.x;
66 y=cur.y;
67 x=find(x);
68 y=find(y);
69 if(x!=y)
70 {
71 Union(x,y);
72 sum+=cur.s;
73 }
74 }
75 printf("%d\n",sum);
76 }
77 return 0;
78 }
79
80
81