HDU 5624 KK's Reconstruction
原创
©著作权归作者所有:来自51CTO博客作者qq636b7aec0b3f1的原创作品,请联系作者获取转载授权,否则将追究法律责任
问题描述
我们可爱的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
这题直接写的暴力,有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;
}