码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-02-07 13:38:48      阅读:209      评论:0      收藏: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;
}


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

标签:

原文地址:http://blog.csdn.net/weizhuwyzc000/article/details/50642666

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!