4 4 1 2 2 2 3 4 1 4 1 3 4 2 2 1 3 1 2
1 0
题解:先按边权从小到大排序,再用并查集枚举。
2014-11-2 22:38:14更新
/* ** 用并查集每次选择一些权值最接近的边组合使得源点跟终点联通 */ #include <stdio.h> #include <string.h> #include <algorithm> #define maxn 210 #define maxm 1010 #define inf 0x3f3f3f3f int pre[maxn], id; struct Node { int u, v, w; } E[maxm]; int min(int a, int b) { return a < b ? a : b; } bool cmp(Node a, Node b) { return a.w > b.w; } int ufind(int k) { int a = k, b; while(pre[k]) k = pre[k]; while(a != k) { b = pre[a]; pre[a] = k; a = b; } return k; } bool same(int a, int b) { return ufind(a) == ufind(b); } void unite(int a, int b) { a = ufind(a); b = ufind(b); if(a != b) pre[a] = b; } void addEdge(int u, int v, int w) { E[id].u = u; E[id].v = v; E[id++].w = w; } int main() { int n, m, i, a, b, c, j, q, ans; while(scanf("%d%d", &n, &m) == 2) { for(i = id = 0; i < m; ++i) { scanf("%d%d%d", &a, &b, &c); addEdge(a, b, c); } std::sort(E, E + m, cmp); scanf("%d", &q); while(q--) { scanf("%d%d", &a, &b); ans = inf; for(i = 0; i < m; ++i) { memset(pre, 0, sizeof(int) * (n + 1)); for(j = i; j < m; ++j) { unite(E[j].u, E[j].v); if(same(a, b)) { ans = min(ans, E[i].w - E[j].w); break; } } if(ans == inf) break; // cut } if(ans == inf) ans = -1; printf("%d\n", ans); } } return 0; }
#include <stdio.h> #include <string.h> #include <limits.h> #include <algorithm> #define maxn 202 #define maxm 1002 using std::sort; using std::min; int pre[maxn]; struct Node{ int u, v, cost; } E[maxm]; int ufind(int k) { int a = k, b; while(pre[k] != -1) k = pre[k]; while(a != k){ b = pre[a]; pre[a] = k; a = b; } return k; } bool cmp(Node a, Node b){ return a.cost < b.cost; } int main() { int n, m, q, a, b, i, j, x, y, ans; while(scanf("%d%d", &n, &m) == 2){ for(i = 0; i < m; ++i) scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].cost); sort(E, E + m, cmp); scanf("%d", &q); while(q--){ scanf("%d%d", &a, &b); ans = INT_MAX; for(i = 0; i < m; ++i){ memset(pre, -1, sizeof(pre)); for(j = i; j < m; ++j){ x = ufind(E[j].u); y = ufind(E[j].v); if(x != y) pre[x] = y; if(ufind(a) == ufind(b)){ ans = min(ans, E[j].cost - E[i].cost); break; } } } if(ans == INT_MAX) printf("-1\n"); else printf("%d\n", ans); } } return 0; }