Problem Description
老 Jack 有一片农田,以往几年都是靠天吃饭的。但是今年老天格外的不开眼,大旱。所以老 Jack 决定用管道将他的所有相邻的农田全部都串联起来,这样他就可以从远处引水过来进行灌溉了。当老 Jack 买完所有铺设在每块农田内部的管道的时候,老 Jack 遇到了新的难题,因为每一块农田的地势高度都不同,所以要想将两块农田的管道链接,老 Jack 就需要额外再购进跟这两块农田高度差相等长度的管道。
现在给出老 Jack农田的数据,你需要告诉老 Jack 在保证所有农田全部可连通灌溉的情况下,最少还需要再购进多长的管道。另外,每块农田都是方形等大的,一块农田只能跟它上下左右四块相邻的农田相连通。
Input
第一行输入一个数字 T(T≤10) ,代表输入的样例组数
输入包含若干组测试数据,处理到文件结束。每组测试数据占若干行,第一行两个正整数 N,M(1≤N,M≤1000) ,代表老 Jack 有N行*M列个农田。接下来 N 行,每行 M 个数字,代表每块农田的高度,农田的高度不会超过100。数字之间用空格分隔。
Output
对于每组测试数据输出两行:
第一行输出:"Case #i:"。i代表第i组测试数据。
第二行输出 1 个正整数,代表老 Jack 额外最少购进管道的长度。
思路:建图,克鲁斯卡尔算法最小生成树,注意建图方法,小心mle就好
代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<set>
using namespace std;
#define LL long long
const int maxn=100005;
const int INF=1000000000;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
int bianshu,dianshu,p[1000005],w[2000005],u[2000005],v[2000005],r[2000005],G[1005][1005];
int cmp(const int i,const int j){
return w[i]<w[j];
}
int find(int x){
if(x==p[x]) return x;
else{
p[x]=find(p[x]);
return p[x];
}
}
int cruscal(){
int ans=0;
for(int i=0 ; i< dianshu ; i++) p[i]=i;
for(int i = 0; i < bianshu; i++) r[i] = i;
sort(r,r+bianshu,cmp);
for(int i = 0; i < bianshu; i++) {
int e = r[i]; int x =find(u[e]); int y = find(v[e]);
if(x!=y) { ans += w[e]; p[x] = y;}
}
return ans;
}
int main(){
//freopen("input.txt", "r", stdin);
int t, kase = 0; scanf("%d", &t);
while(t--){
int n, m; scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) scanf("%d", &G[i][j]);
dianshu = m*n, bianshu = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m - 1; j++) {
u[bianshu] = i*m + j; v[bianshu] = i*m + j + 1;
w[bianshu] = abs(G[i][j] - G[i][j+1]);
bianshu++;
}
for(int j = 0; j < m; j++)
for(int i = 0; i < n - 1; i++) {
u[bianshu] = i*m + j; v[bianshu] = i*m + j + m;
w[bianshu] = abs(G[i][j] - G[i+1][j]);
bianshu++;
}
//for(int i = 0; i < bianshu; i++) printf("%d\n",w[i]);
printf("Case #%d:\n", ++kase);
printf("%d\n",cruscal());
}
return 0;
}