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 107 108
| #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define MAX_N 10000 #define MAX_M 50000 #define INF 2147483647 using namespace std; int n, m, q, cnt; int first[MAX_N+5], d[MAX_N+5], p[MAX_N+5][15], f[MAX_N+5][15]; int father[MAX_N+5]; bool vis[MAX_N+5]; struct Edge { int from, to, c, next; }; Edge G[MAX_M], edge[MAX_M+5]; inline int read() { int ret = 0; char ch = getchar(); while (ch < '0' || ch > '9') ch = getchar(); while (ch >= '0' && ch <= '9') ret = ret*10+ch-'0', ch = getchar(); return ret; } bool cmp (const Edge &a, const Edge &b) { return a.c > b.c; } void Add(int u, int v, int x) { cnt++; edge[cnt].to = v; edge[cnt].c = x; edge[cnt].next = first[u]; first[u] = cnt; } int get_father(int cur) { if (father[cur] != cur) father[cur] = get_father(father[cur]); return father[cur]; } void Kruskal() { sort(G, G+m, cmp); for (int i = 1; i <= n; i++) father[i] = i; for (int i = 0; i < m; i++) { int u = get_father(G[i].from), v = get_father(G[i].to); if (u != v) { father[u] = v; Add(G[i].from, G[i].to, G[i].c); Add(G[i].to, G[i].from, G[i].c); } } } void DFS(int u) { vis[u] = true; for (int i = 1; (1<<i) <= d[u]; i++) { p[u][i] = p[p[u][i-1]][i-1]; f[u][i] = min(f[u][i-1], f[p[u][i-1]][i-1]); } for (int i = first[u]; i; i = edge[i].next) { int v = edge[i].to; if (!vis[v]) { d[v] = d[u]+1; p[v][0] = u; f[v][0] = edge[i].c; DFS(v); } } } int LCA(int a, int b) { int ret = INF, i, j; if (d[a] < d[b]) swap(a, b); for (i = 0; (1<<i) <= d[a]; i++) {} i--; for (j = i; j >= 0; j--) { if (d[a]-(1<<j) >= d[b]) { ret = min(ret, f[a][j]); a = p[a][j]; } } if (a == b) return ret; for (j = i; j >= 0; j--) { if (p[a][j] != p[b][j]) { ret = min(ret, min(f[a][j], f[b][j])); a = p[a][j]; b = p[b][j]; } } return min(ret, min(f[a][0], f[b][0])); } int main() { memset(f, 127, sizeof(f)); n = read(), m = read(); for (int i = 0; i < m; i++) { G[i].from = read(), G[i].to = read(), G[i].c = read(); } Kruskal(); for (int i = 1; i <= n; i++) { if (!vis[i] && father[i] == i) { DFS(i); } } q = read(); for (int i = 0; i < q; i++) { int a, b; a = read(), b = read(); if (get_father(a) != get_father(b)) { printf("-1\n"); } else { printf("%d\n", LCA(a, b)); } } return 0; }
|