标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 16938 Accepted Submission(s): 6435
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 using namespace std; 5 int i, j, n; 6 const int INF = 0x3f3f3f3f; 7 int map[102][102], dis[102], vis[102]; 8 void prime() 9 { 10 memset(vis, 0, sizeof(vis)); //important; 11 int sum = 0; 12 for(i=1; i<=n; i++) 13 dis[i] = map[1][i]; 14 vis[1] = 1; 15 for(i=1; i<n; i++) 16 { 17 int min = INF, temp; 18 for(j=1; j<=n; j++) 19 { 20 if(!vis[j] && dis[j] < min) 21 { 22 min = dis[j]; 23 temp = j; 24 } 25 } 26 vis[temp] = 1; 27 sum += min; 28 for(j=1; j<=n; j++) 29 { 30 if(!vis[j] && dis[j] > map[temp][j]) 31 dis[j] = map[temp][j]; 32 } 33 } 34 printf("%d\n", sum); 35 } 36 int main() 37 { 38 while(~scanf("%d", &n)) 39 { 40 for(i=1; i<=n; i++) 41 for(j=1; j<=n; j++) 42 cin >> map[i][j]; 43 int q; 44 scanf("%d", &q); 45 for(i=1; i<=q; i++) 46 { 47 int a, b; 48 scanf("%d %d", &a, &b); 49 map[a][b] = map[b][a] = 0; 50 } 51 prime(); 52 } 53 return 0; 54 }
//KL;
1 #include <cstdio> 2 #include <algorithm> 3 #include <iostream> 4 using namespace std; 5 int father[110]; 6 int i, j, n; 7 struct via 8 { 9 int s, e, m; 10 } num[10010]; 11 bool cmp(via s, via e) 12 { 13 return s.m < e.m; 14 } 15 int find(int a) 16 { 17 while(a != father[a]) 18 a = father[a]; 19 return a; 20 } 21 void mercy(int a, int b) 22 { 23 int q = find(a); 24 int p = find(b); 25 if(q != p) 26 father[q] = p; 27 } 28 int main() 29 { 30 while(~scanf("%d", &n)) 31 { 32 int a, b, c, k = 0; 33 for(i=1; i<= n; i++) 34 { 35 father[i] = i; 36 for(j=1; j<=n; j++) 37 { 38 scanf("%d", &a); 39 if(j > i) 40 { 41 num[k].s = i; 42 num[k].e = j; 43 num[k].m = a; 44 k++; 45 } 46 } 47 } 48 // printf("%d\n", k); 49 sort(num, num+k, cmp); 50 int q; 51 scanf("%d", &q); 52 for(i=1; i<=q; i++) 53 { 54 int u, v; 55 scanf("%d %d", &u, &v); 56 mercy(u, v); 57 } 58 int sum = 0; 59 for(i=0; i<k; i++) 60 { 61 int q = find(num[i].s); 62 int p = find(num[i].e); 63 if(q != p) 64 { 65 sum += num[i].m; 66 father[q] = p; 67 } 68 } 69 printf("%d\n", sum); 70 } 71 return 0; 72 }
杭电1102--Constructing Roads(简单并查集)
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4699305.html