Hud 1598 find the most comfortable road[枚举 + 并查集]

题目链接:acm.hdu.edu.cn/showproblem.php?pid=1598

题目的意思很是简单。找一条路径,最大速度和最小速度的差值最小。。结点  n <= 200,边m <= 1000。。

根据数据范围,我们可以看出来。。

枚举边的最大值和最小值。。求解答案就可以了。。固定最小值,然后求解满足条件的最大值的最小值。。

判断满足条件的最大值的最小值就是判断连通性就可以。也就是并查集判连通性。。

我们可以发现,有些问题就是根据其数据的大小来找出来其突破口。。

Code:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

const int N = 1004;
const int INF = 0x3f3f3f3f;
struct path
{
    int x, y;
    int v;
}p[N];
int father[N];
int n, m;
bool cmp(path a, path b)
{
    if(a.v < b.v) return true;
    return false;
}

void Init()
{
    for(int i = 1; i <= n; i ++){
        father[i] = i;
    }
}

int find(int x)
{
    if(x != father[x]) father[x] = find(father[x]);
    return father[x];
}

void Union(int x, int y)
{
    int a = find(x);
    int b = find(y);
    if(a != b) father[a] = b;
}

int main()
{
    while(~scanf("%d %d", &n, &m)){
        for(int i = 0; i < m; i ++){
            scanf("%d %d %d", &p[i].x, &p[i].y, &p[i].v);
        }
        sort(p, p + m, cmp);
        int q, st, end;
        scanf("%d", &q);
        while(q --){
            scanf("%d %d", &st, &end);
            int ans = INF;
            for(int i = 0; i < m; i ++){
                Init();
                for(int j = i; j < m; j ++){
                    Union(p[j].x, p[j].y);
                    if(find(st) == find(end)){
                        ans = min(ans, p[j].v - p[i].v);
                    }
                }
            }
            if(ans == INF) puts("-1");
            else printf("%d\n", ans);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值