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
| #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> using namespace std;
const int maxN = 1e5 + 7;
int n, m, q, cnt, head[maxN], fa[maxN], tot, val[maxN], f[maxN][21], depth[maxN];
struct Edge { int from, to, dis; }e[maxN << 1], initEdge[maxN];
inline void add(int u, int v) { e[++cnt].from = head[u]; e[cnt].to = v; head[u] = cnt; }
int Find(int x) { return fa[x] == x? x : fa[x] = Find(fa[x]); }
bool cmp(Edge x, Edge y) { return x.dis > y.dis; }
void dfs(int x) { for(int i = head[x]; i; i = e[i].from) { int y = e[i].to; f[y][0] = x; depth[y] = depth[x] + 1; dfs(y); } }
inline void KruskalTree() { sort(initEdge + 1, initEdge + 1 + m, cmp); for(int i = 1; i <= n; ++i) fa[i] = i; tot = n; for(int i = 1; i <= m; ++i) { int fx = Find(initEdge[i].from), fy = Find(initEdge[i].to); if(fx == fy) continue; val[++tot] = initEdge[i].dis; fa[tot] = fa[fx] = fa[fy] = tot; add(tot, fx); add(tot, fy); } }
inline void initLca() { for(int i = tot; i >= 0; --i) if(!depth[i]) dfs(i); for(int j = 1; (1 << j) <= tot; ++j) for(int i = 1; i <= tot; ++i) f[i][j] = f[f[i][j - 1]][j - 1]; }
int Lca(int x, int y) { if(depth[x] < depth[y]) swap(x, y); int t = (int)(log(depth[x]) / log(2)) + 1; for(int i = t; i >= 0; i--) if(depth[f[x][i]] >= depth[y]) x = f[x][i]; if(x == y) return x; for(int i = t; i >= 0; i--) if(f[x][i] != f[y][i]) x = f[x][i], y = f[y][i]; return f[x][0]; }
int main() { scanf("%d%d", &n, &m); for(int i = 1; i <= m; ++i) scanf("%d%d%d", &initEdge[i].from, &initEdge[i].to, &initEdge[i].dis); KruskalTree(); initLca(); scanf("%d", &q); while(q--) { int x, y; scanf("%d%d", &x, &y); if(Find(x) != Find(y)) printf("-1\n"); else printf("%d\n", val[Lca(x, y)]); } return 0; }
|