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
| #include <bits/stdc++.h>
using namespace std; const int N = 1e6 + 10, M = 2e6 + 10; int h[N], e[M], ne[M], idx; int H[N], E[M], NE[M]; int dep[N], f[N][21]; int dfn[N], low[N], stk[N]; int id[N]; bool cut[N]; int t, tt, cnt; int root; int n, m, q; vector<int> dcc[N];
inline void tarjan(int u) { dfn[u] = low[u] = ++t; stk[++tt] = u; if (h[u] == -1) { dcc[++cnt].push_back(u); return; } int kid = 0; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); if (dfn[u] <= low[v]) { if (u != root || ++kid > 1) cut[u] = true; cnt++; int j; do { j = stk[tt--]; dcc[cnt].push_back(j); } while (v != j); dcc[cnt].push_back(u); } } else low[u] = min(low[u], dfn[v]); } }
inline void add(int h[], int e[], int ne[], int a, int b) { e[idx] = b; ne[idx] = h[a]; h[a] = idx++; }
inline void dfs(int u, int p) { dep[u] = dep[p] + 1, f[u][0] = p; for (int i = 1; (1 << i) <= dep[u]; i++) f[u][i] = f[f[u][i - 1]][i - 1]; for (int i = H[u]; ~i; i = NE[i]) { int v = E[i]; if (v == p) continue; dfs(v, u); } }
inline int lca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = log2(n); i >= 0; i--) if (dep[f[x][i]] >= dep[y]) x = f[x][i]; if (x == y) return x; for (int i = log2(n); 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); memset(h, -1, sizeof h); memset(H, -1, sizeof H); while (m--) { int a, b; scanf("%d%d", &a, &b); add(h ,e, ne, a, b); add(h, e, ne, b, a); } root = 1; tarjan(1); int num = cnt; for (int i = 1; i <= n; i++) if (cut[i]) id[i] = ++num; idx = 0; for (int i = 1; i <= cnt; i++) for (int j = 0; j < dcc[i].size(); j++) { int k = dcc[i][j]; if (cut[k]) { add(H, E, NE, i, id[k]); add(H, E, NE, id[k], i); } else id[k] = i; }
dfs(1, 0); scanf("%d", &q); while (q--) { int s, t; scanf("%d%d", &s, &t); int a = cut[s], b = cut[t]; s = id[s], t = id[t]; int p = lca(s, t); int dist = dep[s] + dep[t] - 2 * dep[p]; printf("%d\n", (dist - (a + b)) / 2 + 2); } return 0; }
|