hdu find the most comfortable road

我想,将速度做一次排序,最后就是多次并查集枚举答案。

因为在排完序之后,减去起点之后的就是本次旅游的最大起伏点,多次枚举求出最小值就是解。

 

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

const int maxn = 205;
const int maxm = 1005;
const int INF = 0xfffffff;
#define min(a,b) ((a)<(b)?(a):(b))

int n,m,start,end;
int ans;
int father[maxn];
struct Edge
{
    int st;
    int en;
    int speed;
}edge[maxm];

bool cmp(Edge x, Edge y )
{
    return  x.speed < y.speed ;
}

int finds(int x)
{
    if(x==father[x]) return x;
    else return finds(father[x]);
}

int main()
{
    int i,j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i=0;i<m;i++) scanf("%d%d%d",&edge[i].st , &edge[i].en , &edge[i].speed );
        sort(edge,edge+m,cmp);
        int T;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d%d",&start,&end);
            int mins = INF;
            for(i=0;i<m;i++)
            {
                for(j=1;j<=n;j++) father[j] = j;
                for(j=i;j<m;j++)
                {
                    int fx = finds(edge[j].st);
                    int fy = finds(edge[j].en);
                    if(fx!=fy) father[fx] = fy;
                    if(finds(start) == finds(end))
                    {
                        mins = min(mins,edge[j].speed - edge[i].speed );
                        break;
                    }
                }
            }
            if(mins == INF) printf("-1\n");
            else printf("%d\n",mins);
        }
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值