标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2063 Accepted Submission(s): 732
#include <stdio.h> #include <math.h> #include <iostream> #include <algorithm> #include <math.h> #include <stdlib.h> #include <string.h> using namespace std; const int N = 1005; const int M = N*N; int n,m; int a[N][N]; int father[M]; struct Edge{ int u,v,w; }edge[2*M]; int _find(int x){ if(x!=father[x]) father[x] = _find(father[x]); return father[x]; } int cmp(Edge a,Edge b){ return a.w<b.w; } int kruskal(int m){ sort(edge+1,edge+m,cmp); int cost = 0; for(int i=1;i<m;i++){ int x = _find(edge[i].u); int y = _find(edge[i].v); if(x!=y){ father[x] = y; cost+=edge[i].w; } } return cost; } int main() { int tcase; scanf("%d",&tcase); int t = 1; while(tcase--){ scanf("%d%d",&n,&m); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ father[i*m+j] = i*m+j; scanf("%d",&a[i][j]); } } int id = 1; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ int u = i*m+j; if(i>0){ int v = (i-1)*m+j; edge[id].u = u; edge[id].v = v; edge[id++].w = abs(a[i][j]-a[i-1][j]); } if(j>0){ int v = i*m+j-1; edge[id].u = u; edge[id].v = v; edge[id++].w = abs(a[i][j]-a[i][j-1]); } } } int cost = kruskal(id); printf("Case #%d:\n%d\n",t++,cost); } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5509903.html