HDU - 1598 find the most comfortable road 并查集+贪心

题目链接

题意:一个 n n n 个点 m m m 条边的图,每次会询问一个点对 ( x , y ) (x,y) (x,y) ,要求从 x x x y y y 的一条路径,这条路径上边的最大值-最小值在所有 x x x y y y 的路径里最小。

思路:要求最大值-最小值最小,这里有两个约束条件,因为 m m m 最大只有 1000 1000 1000 ,所以我们可以考虑暴力枚举最小值的大小来简化题目,把 m m m 条边按权值从小到大排序,对于以第 i i i 条边为最小值,我们可以构建一个新图,按顺序把 i i i m m m 的边加入到集合中,不断加入的过程中判断新图中询问的点对 ( x , y ) (x,y) (x,y) 是否连通,连通的话当前即为第 i i i 条边权值为最小值时的最优解了。判断的方式就是用并查集,把每次加入新图的边的两个节点的父节点连起来。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<queue>
#include<deque>
using namespace std;
#define ll long long
#define PI acos(-1)
#define INF 0x3f3f3f3f
#define NUM 1005
#define debug true
#define lowbit(x) ((-x)&x)
#define ffor(i,d,u) for(int i=(d);i<=(u);++i)
#define _ffor(i,u,d) for(int i=(u);i>=(d);--i)
#define mst(array,Num,Kind,Count) memset(array,Num,sizeof(Kind)*(Count))
const int P = 1e9+7;
int n, m, q;
struct edge
{
    int x,y,v;
    bool operator<(const edge x)const
    {
        return v < x.v;
    }
} e[1005];
int f[205], sz[205];
template <typename T>
void read(T& x)
{
    x=0;
    char c;T t=1;
    while(((c=getchar())<'0'||c>'9')&&c!='-');
    if(c=='-'){t=-1;c=getchar();}
    do(x*=10)+=(c-'0');while((c=getchar())>='0'&&c<='9');
    x*=t;
}
template <typename T>
void write(T x)
{
    int len=0;char c[21];
    if(x<0)putchar('-'),x*=(-1);
    do{++len;c[len]=(x%10)+'0';}while(x/=10);
    _ffor(i,len,1)putchar(c[i]);
}
int find_(int x)
{
    if(f[x] == x)return x;
    return f[x] = find_(f[x]);
}
inline void Union(const int &x, const int &y)
{
    int fx = find_(x);
    int fy = find_(y);
    if (fx == fy)
        return;
    if (sz[fx] > sz[fy])
    {
        sz[fx] += sz[fy];
        f[fy] = fx;
    }
    else
    {
        sz[fy] += sz[fx];
        f[fx] = fy;
    }
}
inline void AC()
{
    int x, y, ans;
    while (scanf("%d", &n) != EOF)
    {
        read(m);
        ffor(i, 1, m) read(e[i].x), read(e[i].y), read(e[i].v);
        sort(e + 1, e + 1 + m);
        read(q);
        while (q--)
        {
            read(x), read(y);
            ans = INF;
            ffor(i, 1, m)
            {
                ffor(j, 1, n) f[j] = j, sz[j] = 1;
                ffor(j, i, m)
                {
                    Union(e[j].x, e[j].y);
                    if (find_(x) == find_(y))
                    {
                        ans = min(ans, e[j].v - e[i].v);
                        break;
                    }
                }
            }
            write((ans != INF) ? ans : -1), putchar('\n');
        }
    }
}
int main()
{
    AC();
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值