From 64580c07e064b5936c06a911591f2e575ebbb2d4 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sun, 2 Jan 2022 19:10:52 +0800 Subject: [PATCH] =?UTF-8?q?P2812=20=E6=A0=A1=E5=9B=AD=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=EF=BC=88=E5=8A=A0=E5=BC=BA=E7=89=88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R66169079 --- Luogu/P2812/P2812.cpp | 70 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Luogu/P2812/P2812.cpp diff --git a/Luogu/P2812/P2812.cpp b/Luogu/P2812/P2812.cpp new file mode 100644 index 00000000..36e1ec13 --- /dev/null +++ b/Luogu/P2812/P2812.cpp @@ -0,0 +1,70 @@ +#include +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +const int N = 100005; + +int n, x, ans1, ans2; +std::vector g[N]; + +// Tarjan +int cnt, dfn[N], low[N]; +int scc_cnt, id[N]; +std::stack st; +bool vis[N]; +int din[N], dout[N]; + +void tarjan(int u) { + dfn[u] = low[u] = ++cnt; + st.push(u); + vis[u] = true; + for (int v : g[u]) { + if (!dfn[v]) { + tarjan(v); + low[u] = std::min(low[u], low[v]); + } else if (vis[v]) { + low[u] = std::min(low[u], dfn[v]); + } + } + if (low[u] == dfn[u]) { + scc_cnt++; + int v; + do { + v = st.top(); + st.pop(); + vis[v] = false; + id[v] = scc_cnt; + } while (v != u); + } +} + +int main() { + cin >> n; + for (int i = 1; i <= n; i++) { + while (cin >> x, x) { + g[i].push_back(x); + } + } + for (int i = 1; i <= n; i++) { + if (!dfn[i]) tarjan(i); + } + for (int i = 1; i <= n; i++) { + for (int v : g[i]) { + if (id[i] != id[v]) { + din[id[v]]++; + dout[id[i]]++; + } + } + } + for (int i = 1; i <= scc_cnt; i++) { + ans1 += !din[i]; + ans2 += !dout[i]; + } + cout << ans1 << endl + << (scc_cnt == 1 ? 0 : std::max(ans1, ans2)) << endl; + return 0; +}