find the most comfortable road(hdu并查集+暴力)

题意:每两个点之间都有一个速度,求a点到b点速度之差最小是多少,如果到达不了输出-1;

思路:先按照速度排序,并查集(最小生成树思路)一直到a,b联通,然后求最大速度和最小速度的差,这个要暴力,每条边都建立最小生成树,最后找到一个最小的速度差

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

int father[220];
int rank[220];
struct bian
{
    int start;
    int end;
    int w;
}B[1002];

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

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

void Union(int x,int y)
{
    int xx = Find_set(x);
    int yy = Find_set(y);

    if(xx == yy)
        return ;
    else
    {
        if(rank[xx] > rank[yy])
        {
            father[yy] = xx;rank[xx] += rank[yy];
        }
        else if(rank[yy] > rank[xx])
        {
            father[xx] = yy,rank[yy] += rank[xx];
        }
        else
        {
            father[yy] = xx ,rank[xx]++;
        }
    }
}

bool cmp(bian a,bian b)
{
    if(a.w < b.w)
        return true;
    else
        return false;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m) != EOF)
    {
        int i;
        for(i = 1; i <= m; i++)
        {
            scanf("%d%d%d",&B[i].start,&B[i].end,&B[i].w);
        }
        sort(B+1,B+m+1,cmp);

        int count;
        scanf("%d",&count);
        while(count--)
        {
            int start,end;
            scanf("%d%d",&start,&end);            
            int i,j,ans=9999999;
            for(i = 1; i <= m; i++)
            {
                Make_set(n);
                for(j = i; j <= m; j++)
                {
                    Union(B[j].start,B[j].end);
                    if(Find_set(start) == Find_set(end))
                    {    
                        break;
                    }
                }
                if(j > m)
                    break;
                if(ans > B[j].w - B[i].w)
                    ans = B[j].w - B[i].w;        
            }

            if(ans != 9999999)    
                printf("%d\n",ans);
            else
                printf("-1\n");
                
        }
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值