标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30542 Accepted Submission(s): 13670
1 #include <iostream> 2 #include <cstdio> 3 #include <string> 4 #include <queue> 5 #include <vector> 6 #include <map> 7 #include <algorithm> 8 #include <cstring> 9 #include <cctype> 10 #include <cstdlib> 11 #include <cmath> 12 #include <ctime> 13 using namespace std; 14 15 const int SIZE = 105; 16 int FATHER[SIZE],N,M,NUM; 17 int MAP[SIZE][SIZE]; 18 struct Node 19 { 20 int from,to,cost; 21 }G[SIZE * SIZE]; 22 23 void ini(void); 24 int find_father(int); 25 void unite(int,int); 26 bool same(int,int); 27 int kruskal(void); 28 bool comp(const Node &,const Node &); 29 int main(void) 30 { 31 while(scanf("%d",&N) && N) 32 { 33 ini(); 34 M = N * (N - 1) / 2; 35 for(int i = 0;i < M;i ++) 36 { 37 scanf("%d%d%d",&G[NUM].from,&G[NUM].to,&G[NUM].cost); 38 NUM ++; 39 } 40 sort(G,G + NUM,comp); 41 kruskal(); 42 } 43 44 return 0; 45 } 46 47 void ini(void) 48 { 49 NUM = 0; 50 for(int i = 1;i <= N;i ++) 51 FATHER[i] = i; 52 } 53 54 int find_father(int n) 55 { 56 if(FATHER[n] == n) 57 return n; 58 return FATHER[n] = find_father(FATHER[n]); 59 } 60 61 void unite(int x,int y) 62 { 63 x = find_father(x); 64 y = find_father(y); 65 66 if(x == y) 67 return ; 68 FATHER[x] = y; 69 } 70 71 bool same(int x,int y) 72 { 73 return find_father(x) == find_father(y); 74 } 75 76 bool comp(const Node & a,const Node & b) 77 { 78 return a.cost < b.cost; 79 } 80 81 int kruskal(void) 82 { 83 int count = 0,ans = 0; 84 85 for(int i = 0;i < NUM;i ++) 86 if(!same(G[i].from,G[i].to)) 87 { 88 unite(G[i].from,G[i].to); 89 count ++; 90 ans += G[i].cost; 91 if(count == N - 1) 92 break; 93 } 94 printf("%d\n",ans); 95 }
标签:
原文地址:http://www.cnblogs.com/xz816111/p/4549502.html