hdu 1598 find the most comfortable road(并查集+枚举图的各边)

本文探讨了在复杂网络环境中,如何运用特定算法提高网络效率和性能,详细介绍了排序算法、动态规划等在资源分配、路径优化等方面的应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



 

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

struct sars
{
   int u,v,w;
}s[1001];

bool cmp(sars a,sars b)
{
    return a.w<b.w;
}
int n,m;
int set[1002];

int findx(int x)
{
      int r = x;int i,j;
      while (set[r] != r) //循环结束,则找到根节点
          r = set[r];
        i = x;
      while (i != r) //本循环修改查找路径中所有节点
      {
          j = set[i];
         set[i] = r;
          i = j;
      }
     return r;
}

void Union(int x,int y)
{
    int fx,fy;
    fx = findx(x);
    fy = findx(y);
    if(fx <= fy)
        set[fy] = fx;
        else set[fx]=fy;
}

int sol(int st,int en)
{
    for(int i=0;i<m;i++){
        Union(s[i].u,s[i].v);
    }
    if(findx(st)!=findx(en))return -1;
    int res=1e9;
    for(int i=0;i<m;i++)
    {
        for(int k=0;k<n;k++)
        set[k]=k;
        for(int j=i;j<m;j++)
        {
            if(s[j].w-s[i].w>=res)continue;
           Union(s[j].u,s[j].v);
            if(findx(st)==findx(en))
            res=min(res,s[j].w-s[i].w);
        }
    }
    return res;
}


int main(){
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int a,b,c;
        for(int i=0;i<m;i++)
        {
           cin>>s[i].u>>s[i].v>>s[i].w;
        }
        sort(s,s+m,cmp);
        cin>>a;
       while (a--)
        {
            cin>>b>>c;
            printf("%d\n",sol(b,c));
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值