問題描述
我們可愛的KK有一道困難的社會性題目:他所在的地區發生了一場大地震(如此老套的出題思路~!),一共有N\left( 2\leq N\leq 2000\right)N(2≤N≤2000)個城市受到了牽連,NN個城市間所有道路都已損壞,現在KK受委托要重修這些道路。然而,經過KK的實地考察發現,很多城市間道路的地基都被破壞了,無法再重修道路,是以可供修建的道路隻有M\left( 0\leq M\leq 15000\right)M(0≤M≤15000)條。KK要用盡量少的道路将所有的城市聯通起來,在此條件下,他希望選擇一種方案,使得方案中最貴道路的價格和最便宜道路的價格的內插補點最小。
輸入描述
第一行一個數T\left( 1\leq T\leq 10\right)T(1≤T≤10),表示資料組數。
每組資料第一行包含兩個整數N\left( 2\leq N\leq 2000\right)N(2≤N≤2000),M\left( 0\leq M\leq 15000\right)M(0≤M≤15000),表示城市的個數和可重修的道路條數。
接下來MM行,每行包含三個整數a,b,c(a\neq b,1\leq c\leq 2*{10}^{9})a,b,c(a≠b,1≤c≤2∗109),表示城市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
#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;
}