原题链接:https://vjudge.net/problem/UVA-1395
分类:图论
备注:kruskal算法,暴力
代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
const int inf = 10000 + 5;
const int maxn = 100 + 5;
const int maxm = 5000 + 5;
int u[maxm], v[maxm], w[maxm], r[maxm], fa[maxn], n, m, cnt[maxn];
bool cmp(const int i, const int j) {
return w[i] < w[j];
}
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int kruskal() {
int ans = inf;
for (int i = 1; i <= m; i++)r[i] = i;
sort(r + 1, r + 1 + m, cmp);
for (int i = 1; i <= n; i++) {
fa[i] = i; cnt[i] = 1;
}
for (int i = 1; i <= m; i++) {
int e = r[i];
int x = find(u[e]), y = find(v[e]);
if (x != y) {
fa[y] = x;
ans += w[e];
cnt[x] += cnt[y];
}
}
if (cnt[find(1)] != n)return -1;
int maxL = m - n + 2;
for (int L = 1; L <= maxL; L++) {
for (int R = L + n - 2; R <= m; R++) {
for (int i = 1; i <= n; i++) {
fa[i] = i; cnt[i] = 1;
}
for (int i = L; i <= R; i++) {
int e = r[i];
int x = find(u[e]), y = find(v[e]);
if (x != y) {
fa[y] = x; cnt[x] += cnt[y];
}
}
if (cnt[find(1)] == n) {
ans = min(ans, w[r[R]] - w[r[L]]);
break;//已经找到对应L可能的最小值
}
}
}
return ans;
}
int main(void) {
while (~scanf("%d %d", &n, &m) && n) {
for (int i = 1; i <= m; i++)
scanf("%d %d %d", &u[i], &v[i], &w[i]);
printf("%d\n", kruskal());
}
return 0;
}