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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| #include <cstdio> #include <algorithm> using namespace std; const int N = 1e4 + 10, M = 2e4 + 10, inf = 1e5; int n, m, q, d[N], p[N], f[N], w[N], rt[N]; int idx, hd[N], nxt[M], edg[M], wt[M]; int stmp, sz[N], son[N], dfn[N], top[N], rnk[N]; struct Edge { int u, v, w; bool operator<(Edge &_) { return w > _.w; } } e[M]; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } struct Node { int l, r; int mn; } tr[N << 2]; void pushup(int x) { tr[x].mn = min(tr[x << 1].mn, tr[x << 1 | 1].mn); } void build(int x, int l, int r) { tr[x].l = l; tr[x].r = r; if (l == r) { tr[x].mn = w[rnk[l]]; return; } int mid = l + r >> 1; build(x << 1, l, mid); build(x << 1 | 1, mid + 1, r); pushup(x); } int query(int x, int l, int r) { if (tr[x].l >= l && tr[x].r <= r) return tr[x].mn; int res = inf; int mid = tr[x].l + tr[x].r >> 1; if (l <= mid) res = min(res, query(x << 1, l, r)); if (r > mid) res = min(res, query(x << 1 | 1, l, r)); return res; } int queryPath(int x, int y) { int res = inf; while (top[x] != top[y]) { if (d[top[x]] < d[top[y]]) swap(x, y); res = min(res, query(1, dfn[top[x]], dfn[x])); x = p[top[x]]; } if (x == y) return res; if (d[x] > d[y]) swap(x, y); return min(res, query(1, dfn[x] + 1, dfn[y])); } void dfs1(int x) { sz[x] = 1; son[x] = -1; for (int i = hd[x]; ~i; i = nxt[i]) if (!d[edg[i]]) { d[edg[i]] = d[x] + 1; p[edg[i]] = x; w[edg[i]] = wt[i]; dfs1(edg[i]); sz[x] += sz[edg[i]]; if (son[x] == -1 || sz[edg[i]] > sz[son[x]]) son[x] = edg[i]; } } void dfs2(int x, int t) { dfn[x] = ++stmp; rnk[stmp] = x; top[x] = t; if (son[x] == -1) return; dfs2(son[x], t); for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != p[x] && edg[i] != son[x]) dfs2(edg[i], edg[i]); } void add(int a, int b, int c) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) hd[i] = -1; for (int i = 1; i <= n; i++) f[i] = i; for (int i = 0; i < m; i++) scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w); sort(e, e + m); for (int i = 0; i < m; i++) if (find(e[i].u) != find(e[i].v)) { f[f[e[i].u]] = f[e[i].v]; add(e[i].u, e[i].v, e[i].w); add(e[i].v, e[i].u, e[i].w); } for (int i = 1; i <= n; i++) if (!dfn[i]) { d[i] = 1; dfs1(i); dfs2(i, i); } build(1, 1, n); scanf("%d", &q); for (int x, y; q; q--) { scanf("%d%d", &x, &y); if (find(x) != find(y)) puts("-1"); else printf("%d\n", queryPath(x, y)); } return 0; }
|