HDU 5253 连接的管道 (最小生成树)

时间:2023-01-21 18:46:35

连接的管道

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 653    Accepted Submission(s): 268

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 额外最少购进管道的长度。

 
Sample Input
2
4 3
9 12 4
7 8 56
32 32 43
21 12 12
2 3
34 56 56
12 23 4
 
Sample Output
Case #1:
82
Case #2:
74
 
 
 
以高度差作为权值,跑一次最小生成树。
 
 #include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std; const int SIZE = ;
struct Node
{
int from,to,cost;
}G[SIZE * SIZE * ];
int MAP[SIZE][SIZE],FATHER[SIZE * SIZE];
int N,M,NUM; void ini(void);
int find_father(int);
void unite(int,int);
bool same(int,int);
bool comp(const Node &,const Node &);
long long kruskal(void);
int main(void)
{
int t;
int count = ; scanf("%d",&t);
while(t --)
{
count ++;
scanf("%d%d",&N,&M);
ini();
for(int i = ;i <= N;i ++)
for(int j = ;j <= M;j ++)
scanf("%d",&MAP[i][j]);
for(int i = ;i <= N;i ++)
for(int j = ;j <= M;j ++)
{
if(j + <= M)
{
G[NUM].from = (i - ) * M + j;
G[NUM].to = (i - ) * M + j + ;
G[NUM].cost = abs(MAP[i][j] - MAP[i][j + ]);
NUM ++;
}
if(i + <= N)
{
G[NUM].from = (i - ) * M + j;
G[NUM].to = (i) * M + j;
G[NUM].cost = abs(MAP[i][j] - MAP[i + ][j]);
NUM ++;
}
}
printf("Case #%d:\n%lld\n",count,kruskal());
} return ;
} void ini(void)
{
NUM = ;
for(int i = ;i <= N * M;i ++)
FATHER[i] = i;
} int find_father(int n)
{
if(n == FATHER[n])
return n;
return FATHER[n] = find_father(FATHER[n]);
} void unite(int x,int y)
{
x = find_father(x);
y = find_father(y); if(x == y)
return ;
FATHER[x] = y;
} bool same(int x,int y)
{
return find_father(x) == find_father(y);
} bool comp(const Node & a,const Node & b)
{
return a.cost < b.cost;
} long long kruskal(void)
{
long long ans = ;
int count = ; sort(G,G + NUM,comp);
for(int i = ;i < NUM;i ++)
if(!same(G[i].from,G[i].to))
{
ans += G[i].cost;
unite(G[i].from,G[i].to);
if(count == N * M - )
break;
}
return ans;
}