1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include <iostream> #include <cstdio> #include <algorithm> #include <ctype.h> #include <cstring> using namespace std; const int maxn = 50010; inline int read() { int x = 0, w = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') w = -1; c = getchar(); } while (isdigit(c)) x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); return x * w; } int n, m, t; int fa[maxn], e[maxn], rank[maxn]; struct data { int x, y, z; } a[maxn];
inline bool cmp(data a, data b) { return a.z < b.z; } inline int find(int x) { return fa[x] == x ? x : find(fa[x]); } inline void kruskal() { int s = 0, f1, f2; for (int i = 1; i <= n; i++) fa[i] = i, rank[i] = 1; for (int i = 1; i <= m; i++) { f1 = find(a[i].x); f2 = find(a[i].y); if (f1 != f2) { if (rank[f1] < rank[f2]) { fa[f1] = f2; e[f1] = a[i].z; rank[f2] = max(rank[f2], rank[f1] + 1); } else { fa[f2] = f1; e[f2] = a[i].z; rank[f1] = max(rank[f1], rank[f2] + 1); } s++; } if (s == n - 1) break; } } int c[maxn]; int query(int x, int y) { for (int i = 1; i <= n; i++) c[i] = -1; int tmp = 0, ans = 0; while (1) { c[x] = tmp; if (fa[x] == x) break; tmp = max(tmp, e[x]); x = fa[x]; } while (1) { if (c[y] >= 0) { ans = max(ans, c[y]); break; } if (fa[y] == y) break; ans = max(ans, e[y]); y = fa[y]; } return ans; } int main() { while (~scanf("%d%d", &n, &m)) { for (int i = 1; i <= m; i++) { a[i] = (data){read(), read(), read()}; } sort(a + 1, a + 1 + m, cmp); kruskal(); t = read(); for (int x, y, i = 1; i <= t; i++) { x = read(), y = read(); printf("%d\n", query(x, y)); } } return 0; }
|