KK's Reconstruction

Description

Our lovely KK has a difficult Social problem. 
A big earthquake happened in his area. 
 cities have been implicated. All the roads between them are destroyed. 
Now KK was commissioned to rebuild these roads. 
However, after investigation,KK found that some roads are too damaged to rebuild. 
Therefore, there are only 
 roads can be rebuilt. 
KK needs to make sure that there is a way between any two cities, and KK wants to rebuild roads as few as possible. 
With rebuilding minimal number of roads, he also wants to minimize the difference between the price of the most expensive road been built and the cheapest one.

Input

The first line of the input file contains an integer 
, which indicates the number of test cases. 

For each test case,The first line includes two integers 

The next 
 lines include three integers 
,indicating there is a undirected edge between 
 and 
,the cost is 
.

Output

For each test case, output the smallest difference between the price of the most expensive road and the cheapest one.If there is no legal solution, then output -1.

Sample Input

        
        
2
5 10
1 2 9384
1 3 887
1 5 6916
1 4 2778
2 4 8336
2 3 7794
2 5 5387
4 5 1422
3 4 493
3 5 6650
2 0

Sample Output

        
        
1686
-1

题意:有N个城市,M 条路,让你去找路使得所有的城市都连通,并且求所找的路使得最大的边和最小的边的差值最小
思路:这种保证连通集的用最小生成树(主要是连通所有的结点,求的最小的花费),这里使用kruskal()写法,基于并查集的写法,此外还有一种prim()基于最短路迪杰斯特拉的写法。我们来枚举最小的边,让其构成连通,利用 kruskal()得到最大的边,然后最小的差值。
AC代码:
#include <iostream>
#include <map>
#include <vector>
#include <cstdio>
#include <queue>
#include <algorithm>

using namespace std;

const int MAX_N = 2005;
const int INF = 0x7fffffff;

struct point {
    int s;
    int e;
    int val;
    bool operator < (const point &b) const {
        return val < b.val;
    }
} p[15005];
int fa[MAX_N];
int n,m;
int flag;

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

int kruscal(int k) {
    int maxcost = 0;
    for(int i = 0;i <= n;i++){
        fa[i] = i;
    }
    int t = n;
    for(int i = k; i < m; i++) {
        int fx = found(p[i].s);
        int fy = found(p[i].e);
        if(fx != fy) {
            fa[fx] = fy;
            t--;
            maxcost = max(maxcost,p[i].val);
        }
    }
    return t==1?maxcost:0;
}

int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%d%d",&n,&m);
        for(int i = 0; i < m; i++) {
            scanf("%d%d%d",&p[i].s,&p[i].e,&p[i].val);
        }
        sort(p,p+m);
        int ans = INF;
        flag = 1;
        for(int i = 0; i < m; i++) {
            int ans2 = kruscal(i);
            if(ans2 == 0){
                break;
            }
            ans = min(ans,ans2-p[i].val);
        }
        printf("%d\n",ans != INF?ans:-1);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值