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