HDU 5624 KK's Reconstruction(最小生成树)

101 篇文章 0 订阅
53 篇文章 0 订阅

题目链接:点击打开链接

题意:n个城市, m条可以修建的路, 修每条路有一个费用, 要求修建路将n个城市全部联通,并且最大费用减去最小费用最小。

思路:枚举最小边, 然后重新求一遍最小生成树,复杂度m^2, 出的数据水了, 昨天BC水过了。。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int mod = 1000000000 + 7;
const ll INF = (ll)2100000000;
const int maxn = 2000 + 10;
const int maxm = 15000 + 10;
int T,n,m,p[maxn];
struct node {
    ll a, b, c;
    bool operator < (const node& rhs) const {
        return c < rhs.c;
    }
}a[maxm];
int _find(int x) { return p[x] == x ? x : p[x] = _find(p[x]); }
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&n,&m);
        for(int i=0;i<m;i++) {
            scanf("%d%d%d",&a[i].a,&a[i].b,&a[i].c);
        }
        sort(a,a+m);
        ll ans = INF;
        for(int i=1;i<=n;i++) p[i] = i;
         for(int i=0;i<m;i++) {
            ll minv = a[i].c, maxv = a[i].c;
            ll cnt = 1;
            for(int j=1;j<=n;j++) p[j] = j;
            for(int j=i;j<m;j++) {
                int x = _find(a[j].a);
                int y = _find(a[j].b);
                if(x != y) {
                    p[x] = y;
                    maxv = a[j].c;
                    ++cnt;
                }
                if(cnt == n) break;
            }
            if(cnt == n) ans = min(ans, maxv - minv);
        }
        if(ans == INF) printf("-1\n");
        else printf("%I64d\n",ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值