HDU - 5253 - 连接的管道


题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5253

题目描述

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

解题思路

把每块田地标号,在init函数里用一个巧妙的方法,因为要连接所有的田地,采用搜索的方法,但是不需要4个方向,两个方向就足够了,数组一定要开大!!!剩下的就是最小生成树的内容了
最小生成树

AC代码

#include<iostream>
#include<algorithm>
#include<cmath>
#define maxn 1010

using namespace std;

int kase, index;
int n, m;
int pre[5000005];
int map[maxn][maxn];
int to[4][2] = {{0,1},{1,0}};

struct node {
    int a, b, dis;
}cnt[5000005];

void init() {
    for(int x = 0; x < n; x++) {
    for(int y = 0; y < m; y++) {
    for(int k = 0; k <= 1; k++) {
        int tx = x + to[k][0];
        int ty = y + to[k][1];
        if(tx>=0 && ty>=0 && tx<n && ty<m) {
            cnt[kase].a = x * m + y;
            cnt[kase].b = tx * m + ty;
            cnt[kase].dis = abs(map[x][y] - map[tx][ty]);
            kase ++;
        }
    }
    }
    }
}

int find(int x) {
    return pre[x] == x ? x : pre[x] = find(pre[x]);
}

bool cmp(node a, node b) {
    return a.dis < b.dis;
}

int kruskal () {
    int ans = 0;
    sort(cnt, cnt+kase, cmp);
    for(int i = 0; i < kase; i++) {
        int x = find(cnt[i].a);
        int y = find(cnt[i].b);
        if(x != y) {
            ans += cnt[i].dis;
            pre[x] = y;
        }
    }
    return ans;
} 

int main () {
    int t, l = 1;
    scanf("%d", &t);
    while(t--) {
        kase = 0;
        scanf("%d %d", &n, &m);
        for(int i = 0; i < n; i++) 
            for(int j = 0; j < m; j++) 
                scanf("%d", &map[i][j]);
        int o = n*m;
        for(int i = 0; i <= o; i++) pre[i] = i;
        init();
        printf("Case #%d:\n%d\n", l, kruskal());
        l++;
    }
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值