首页 > 代码库 > 123
123
#include <cstdio>
#include <algorithm>
#define MAXN 10005
#define MAXM 50005
#define INF 1 << 30
using namespace std;
int n, u, v, w, q, o;
int s, t, set[MAXN], m;
struct Edge {
int u, v, w;
};
Edge e[MAXN * 2];
struct Cmp {
bool operator () (Edge a, Edge b) {
return (a.w > b.w);
}
} x;
void addEdge(int u, int v, int w) {
o++, e[o] = (Edge) {u, v, w};
}
int check(int x) {
return (set[x] == x ? x : set[x] = check(set[x]));
}
int work() {
int ans, get = 0;
for (int i = 1; i <= m; i++) {
if (check(s) == check(t)) {
get = 1;
break;
}
int c1 = check(e[i].u), c2 = check(e[i].v);
if (c1 != c2) set[c1] = c2, ans = e[i].w;
}
return get ? ans : -1;
}
int main() {
freopen("truck.in", "r", stdin);
freopen("truck.out", "w", stdout);
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) scanf("%d %d %d", &u, &v, &w), addEdge(u, v, w);
sort(e + 1, e + m + 1, x);
scanf("%d", &q);
while (q--) {
scanf("%d %d", &s, &t);
for (int i = 1; i <= n; i++) set[i] = i;
printf("%d\n", work());
}
return 0;
}
123