From dd561472e78af4b937cdd4f332bf0ab1d2abebb1 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Wed, 29 Dec 2021 19:45:56 +0800 Subject: [PATCH] =?UTF-8?q?1174.=20=E5=8F=97=E6=AC=A2=E8=BF=8E=E7=9A=84?= =?UTF-8?q?=E7=89=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.acwing.com/problem/content/submission/code_detail/9575745/ --- AcWing/1174/1174.cpp | 78 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 AcWing/1174/1174.cpp diff --git a/AcWing/1174/1174.cpp b/AcWing/1174/1174.cpp new file mode 100644 index 00000000..589a213f --- /dev/null +++ b/AcWing/1174/1174.cpp @@ -0,0 +1,78 @@ +#include +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +// Limits +const int N = 10005; + +int n, m, a, b; +std::vector g[N]; + +// Tarjan +int cnt, dfn[N], low[N]; +int scc_cnt, id[N], siz[N]; +int dout[N]; +bool vis[N]; +std::stack st; + +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 (dfn[u] == low[u]) { + scc_cnt++; + int v; + do { + v = st.top(); + st.pop(); + vis[v] = false; + id[v] = scc_cnt; + siz[scc_cnt]++; + } while (v != u); + } +} + +int main() { + cin >> n >> m; + for (int i = 1; i <= m; i++) { + cin >> a >> b; + g[a].push_back(b); + } + 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]) { + dout[id[i]]++; + } + } + } + int z = 0, sum = 0; + for (int i = 1; i <= scc_cnt; i++) { + if (!dout[i]) { + z++; + sum += siz[i]; + if (z > 1) { + sum = 0; + break; + } + } + } + cout << sum << endl; + return 0; +}