HDU 5624 KK's Reconstruction

33 篇文章 0 订阅
22 篇文章 0 订阅
问题描述
我们可爱的KK有一道困难的社会性题目:他所在的地区发生了一场大地震(如此老套的出题思路~!),一共有N\left( 2\leq N\leq 2000\right)N(2N2000)个城市受到了牵连,NN个城市间所有道路都已损坏,现在KK受委托要重修这些道路。然而,经过KK的实地考察发现,很多城市间道路的地基都被破坏了,无法再重修道路,因此可供修建的道路只有M\left( 0\leq M\leq 15000\right)M(0M15000)条。KK要用尽量少的道路将所有的城市联通起来,在此条件下,他希望选择一种方案,使得方案中最贵道路的价格和最便宜道路的价格的差值最小。
输入描述
第一行一个数T\left( 1\leq T\leq 10\right)T(1T10),表示数据组数。
每组数据第一行包含两个整数N\left( 2\leq N\leq 2000\right)N(2N2000)M\left( 0\leq M\leq 15000\right)M(0M15000),表示城市的个数和可重修的道路条数。
接下来MM行,每行包含三个整数a,b,c(a\neq b,1\leq c\leq 2*{10}^{9})a,b,c(ab,1c2109),表示城市aa,bb之间可以修建一条价格为cc的无向道路。
输出描述
对于每一个数据输出一个整数,表示最贵道路的价格和最便宜道路的价格的最小差值,如果不存在合法的方案,则输出-1。
输入样例
2
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
2 0
输出样例
1686

-1

这题直接写的暴力,有6秒,姿势对了也可以过

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<iostream>
#include<algorithm>
#include<bitset>
#include<functional>
using namespace std;
typedef long long LL;
const int maxn = 2005;
const int INF = 0x7FFFFFFF;
int T, n, m, fa[maxn];

struct point
{
    int x, y, cost;
    void read(){ scanf("%d%d%d", &x, &y, &cost); }
    bool operator<(const point&a)const{ return cost < a.cost; };
}a[maxn * 10];

int get(int x)
{
    return fa[x] == x ? fa[x] : fa[x] = get(fa[x]);
}

int main(){
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%d", &n, &m);
        for (int i = 0; i < m; i++) a[i].read();
        sort(a, a + m);
        int ans = INF;
        for (int i = 0; i < m; i++)
        {
            int cnt = n - 1, res;
            for (int j = 1; j <= n; j++) fa[j] = j;
            for (int j = i; j < m; j++)
            {
                int fx = get(a[j].x), fy = get(a[j].y);
                if (fx == fy) continue; else fa[fx] = fy;
                if (!(--cnt)) { res = a[j].cost - a[i].cost; break; }
            }
            if (cnt) break;
            ans = min(ans, res);
        }
        if (ans == INF) printf("-1\n"); else printf("%d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值