标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1455 Accepted Submission(s):
549
1 #include <cmath> 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 int num[1100][1100],father[1001000], ac[4][2] ={0, 1, 0, -1, -1, 0, 1, 0}; 8 struct node 9 { 10 int a, b; 11 int w; 12 } map[2001000]; 13 bool cmp(node a, node b) 14 { 15 return a.w < b.w; 16 } 17 void init(int n) 18 { 19 for(int i = 1; i <= n; i++) 20 father[i] = i; 21 } 22 int find(int a) 23 { 24 int r, k, j; 25 r = a; 26 while(r != father[r]) 27 r = father[r]; 28 j = a; 29 while(j != r) 30 { 31 k = father[j]; 32 father[j] = r; 33 j = k; 34 } 35 return r; 36 } 37 bool mercy(int a, int b) 38 { 39 int q = find(a); 40 int p = find(b); 41 if(q != p) 42 { 43 father[q] = p; 44 return true; 45 } 46 else 47 return false; 48 } 49 int main() 50 { 51 // freopen("input.txt","r",stdin); 52 int t, temp = 1; 53 scanf("%d", &t); 54 while(t--) 55 { 56 int n, m, p = 0; 57 scanf("%d %d", &n, &m); 58 init(n*m); 59 // for(int i = 1; i <= n; i++) 60 // for(int j = 1; j <= m; j++) 61 // scanf("%d", &num[i][j]); 62 for(int i = 1; i <= n; i++) /***************/ 63 { 64 for(int j = 1; j <= m; j++) 65 { 66 scanf("%d", &num[i][j]); 67 int a = (i-1)*m + j; 68 if(j > 1) 69 { 70 map[p].a = a; 71 map[p].b = a - 1; 72 map[p++].w = abs(num[i][j] - num[i][j-1]); 73 } 74 if(i > 1) 75 { 76 map[p].a = a; 77 map[p].b = a - m; 78 map[p++].w = abs(num[i][j] - num[i-1][j]); 79 } 80 } 81 } /*********************/ 82 int sum = 0; 83 sort(map, map + p, cmp); 84 int tt = 0; 85 for(int i = 0; i < p; i++) 86 { 87 if(mercy(map[i].a, map[i].b)) 88 { 89 sum += map[i].w; 90 tt++; 91 } 92 if(tt >= n*m-1) //小优化; 93 break; 94 } 95 printf("Case #%d:\n", temp++); 96 printf("%d\n", sum); 97 } 98 return 0; 99 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4733445.html