跳到正文

个人记录

HDU 5253 连接的管道

sakuya726约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

原题链接

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


下面是代码

C++
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define rg register
#define MAXN 1025
#define min(a,b) (a)<(b)?(a):(b)
#define INF 0x3f3f3f3f
int dx[4]={0,1,-1,0};
int dy[4]={1,0,0,-1};
int n,m,Map[MAXN][MAXN],T,father[MAXN*MAXN];
int tot,sum;
struct node
{
	int a,b;
	int cost;
}s[MAXN*MAXN*4];
inline int read()
{
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9')
    {
        if(c=='-')
        {
            f=-1;
        }
        c=getchar();
    }
    while(c<='9'&&c>='0')
    {
        x=(x<<1)+(x<<3)+(c^48);
        c=getchar();
    }
    return x*f;
}
template <typename qaq >inline void print(qaq x)
{
    if(x<0)
    {
        x=-x;
        putchar('-');
    }
    if(x>=10)
    {
        print(x/10);
    }
    putchar(x%10+'0');
}
inline int find(int x)
{
	if(father[x]==-1)
	{
		return x;
	}
	else
	{
		return father[x]=find(father[x]);
	}
}
bool cmp(node x,node y)
{
	return x.cost<y.cost;
}
inline int kruskal()
{
	int ans=0;
    for(rg int i=1;i<=tot;++i)
    {
        int xx=find(s[i].a) ;
        int yy=find(s[i].b) ;
        if(xx==yy)
		{
			continue;
		}
        father[xx]=yy;
        ans+=s[i].cost;
    }
    return ans ;
}
int main()
{
	T=read();
	for(rg int t=1;t<=T;++t)
	{
		n=read();
		m=read();
		tot=0;
		memset(father,-1,sizeof(father));
		for(rg int i=1;i<=n;++i)
		{
			for(rg int j=1;j<=m;++j)
			{
				Map[i][j]=read();
			}
		}
		for(rg int i=1;i<=n;++i)
		{
			for(rg int j=1;j<=m;++j)
			{
				for(rg int k=0;k<4;++k)
				{
					int nx=i+dx[k];
					int ny=j+dy[k];
					if(nx<1||nx>n||ny<1||ny>m)
					{
						continue;
					}
					if(Map[i][j]>=Map[nx][ny])
					{
						s[++tot].a=i*m+j;
						s[tot].b=nx*m+ny;
						s[tot].cost=Map[i][j]-Map[nx][ny];
					}
				}
			}
		}
		sort(s+1,s+1+tot,cmp);
		sum=kruskal();
		printf("Case #%d:\n",t);
		print(sum);
		puts("");
	}
}
原文