本文版权归点A点C和博客园共有,欢迎转载,但必须保留此段声明,并给出原文连接,谢谢合作!!!

zoj 1372 Networking poj1287

 1 #include <iostream>
 2 #include<string.h>
 3 #include<stdio.h>
 4 #include<algorithm>
 5 #define MAXN 55
 6 #define MAXM 10000
 7 
 8 using namespace std;
 9 struct edge
10 {
11     int u,v,w;
12 }edges[MAXM];
13 int parent[MAXN];
14 int sumweight;
15 int N,M;
16 int i,j;
17 void UFset()
18 {
19     for(i=1;i<=N;i++)
20     {
21         parent[i]=-1;
22     }
23 }
24 int Find(int x)
25 {
26     int s;
27     for(s=x; parent[s]>=0; s=parent[s]);
28     while(s!=x)
29     {
30         int tmp=parent[x];
31         parent[x]=s;
32         x=tmp;
33     }
34     return s;
35 }
36 void Union(int R1,int R2)
37 {
38     int r1=Find(R1);
39     int r2=Find(R2);
40     int tmp=parent[r1]+parent[r2];
41     if(parent[r1]<parent[r2])
42     {
43         parent[r2]=r1;
44         parent[r1]=tmp;
45     }
46     else
47     {
48         parent[r1]=r2;
49         parent[r2]=tmp;
50     }
51 }
52 int cmp(const void *a,const void *b)
53 {
54     edge aa=*(const edge *)a;
55     edge bb=*(const edge *)b;
56     if(aa.w>bb.w)
57     return 1;
58     else return -1;
59 }
60 void Kruskal()
61 {
62     int u,v;
63     UFset();
64     int num=0;
65     for(i=0; i<M; i++)
66     {
67         u=edges[i].u;
68         v=edges[i].v;
69         if(Find(v)!=Find(u))
70         {
71             sumweight+=edges[i].w;
72             num++;
73             Union(u,v);
74         }
75         if(num>=N-1) break;
76     }
77 
78 }
79 
80 int main()
81 {
82     while(1)
83     {
84         scanf("%d",&N);
85         if(N==0)break;
86         scanf("%d",&M);
87         for(i=0; i<M; i++)
88         {
89             scanf("%d%d%d",&edges[i].u,&edges[i].v,&edges[i].w);
90         }
91         qsort(edges,M,sizeof(edges[0]),cmp);
92         sumweight=0;
93         Kruskal();
94         printf("%d\n",sumweight);
95     }
96 
97     return 0;
98 }
View Code

 

posted on 2013-08-07 15:58  点A点C  阅读(202)  评论(0编辑  收藏  举报

导航