inline ll rd(){ ll x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
#define N 200007 vector<int> e[N]; int deg[N], vis[N], bl[N], col; queue<int> q;
voiddfs(int u, int fa){ for (auto v : e[u]) if (v != fa && !bl[v]) { bl[v] = bl[u]; dfs(v, u); } }
intmain(){ int n = rd(); for (int i = 1; i <= n; ++i) { int u = rd(), v = rd(); e[u].pb(v); e[v].pb(u); ++deg[u]; ++deg[v]; } for (int i = 1; i <= n; ++i) if (deg[i] == 1) q.push(i); while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = 1; for (auto v : e[u]) { --deg[v]; if (deg[v] == 1) q.push(v); } } for (int i = 1; i <= n; ++i) if (!vis[i]) bl[i] = ++col; for (int i = 1; i <= n; ++i) if (!vis[i]) dfs(i, i); for (int q = rd(); q; --q) { int u = rd(), v = rd(); puts(bl[u] == bl[v] ? "Yes" : "No"); } return0; }
inline ll rd(){ ll x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
#define N 1000007 int a[N], b[N], indeg[N], vis[N], cnt; vector<int> e[N]; queue<int> q; map<int, int> m, m0; // val cnt set<int> s;
voiddfs(int u){ vis[u] = 1; s.insert(a[u]); for (auto v : e[u]) { if (!vis[v]) dfs(v); } }
inlinevoidwork(){ int n = rd(); m.clear(); m0.clear(); cnt = 0; for (int i = 1; i <= n; ++i) { a[i] = rd(); vis[i] = 0; indeg[i] = 0; e[i].clear(); m0[a[i]]++; } for (int i = 1; i <= n; ++i) { b[i] = rd(); e[i].pb(b[i]); ++indeg[b[i]]; } for (int i = 1; i <= n; ++i) if (!indeg[i]) q.push(i); while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = 1; for (auto v : e[u]) { --indeg[v]; if (!indeg[v]) q.push(v); } } int ans = 1e7; for (int i = 1; i <= n; ++i) if (!vis[i]) { ++cnt; dfs(i); for (auto val : s) m[val]++; s.clear(); } for (auto node : m) { int val = node.first, cntt = node.second; if (cntt != cnt) continue; ans = min(ans, n - m0[val]); } if (ans == 1e7) puts("-1"); elseprintf("%d\n", ans); }
intmain(){ for (int t = rd(); t; --t) work(); return0; }
Post title:基环树
Post author:Eva.Q
Create time:2022-08-28 11:15:05
Post link:https://qyy/2022/08/28/Algorithm/Base-ring-tree/
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.