| # |
Author |
Problem |
Lang |
Verdict |
Time |
Memory |
Sent |
Judged |
|
| 186095525 |
Practice:
Alex_Wei |
1763F
- 39
|
C++17 (GCC 9-64)
|
Accepted
|
670 ms
|
70936 KB
|
2022-12-20 14:30:00 |
2022-12-20 14:30:00 |
|
#include <bits/stdc++.h>
using namespace std;
constexpr int K = 19;
constexpr int N = 4e5 + 5;
int n, m, q, node;
int fa[N], w[N], anc[K][N], s[N], dep[N];
int dn, dfn[N], low[N], top, stc[N];
vector<int> e[N], g[N];
void tarjan(int id) {
dfn[id] = low[id] = ++dn;
stc[++top] = id;
for(int it : e[id]) {
if(!dfn[it]) {
tarjan(it);
low[id] = min(low[id], low[it]);
if(low[it] >= dfn[id]) {
g[++node].push_back(id);
g[id].push_back(node);
for(int x = 0; x != it; ) {
g[node].push_back(x = stc[top--]);
g[x].push_back(node);
}
}
}
else low[id] = min(low[id], dfn[it]);
}
}
void dfs1(int id, int ff) {
fa[id] = ff;
for(int it : g[id]) {
if(it != ff) dfs1(it, id);
}
}
void dfs2(int id, int ff) {
anc[0][id] = ff;
dep[id] = dep[ff] + 1;
s[id] = s[ff] + w[id];
for(int it : g[id]) {
if(it != ff) dfs2(it, id);
}
}
int lca(int u, int v) {
if(dep[u] < dep[v]) swap(u, v);
for(int i = K - 1; ~i; i--) {
if(dep[anc[i][u]] >= dep[v]) u = anc[i][u];
}
if(u == v) return u;
for(int i = K - 1; ~i; i--) {
if(anc[i][u] != anc[i][v]) u = anc[i][u], v = anc[i][v];
}
return anc[0][u];
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m, node = n;
for(int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
e[u].push_back(v);
e[v].push_back(u);
}
tarjan(1), dfs1(1, 0);
for(int i = 1; i <= n; i++)
for(int it : e[i]) {
if(i > it) continue;
if(fa[i] == fa[it]) w[fa[i]]++;
else if(fa[fa[i]] == it) w[fa[i]]++;
else w[fa[it]]++;
}
for(int i = n + 1; i <= node; i++) {
if(w[i] == 1) w[i] = 0;
}
dfs2(1, 0);
for(int i = 1; i < K; i++)
for(int j = 1; j <= node; j++)
anc[i][j] = anc[i - 1][anc[i - 1][j]];
cin >> q;
while(q--) {
int a, b;
cin >> a >> b;
int d = lca(a, b);
cout << s[a] + s[b] - s[d] - s[fa[d]] << "\n";
}
return 0;
}
Click to see test details