From 2aa67b0bb8f3d5791218626aa104d1eb739f13fc Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sat, 1 Jan 2022 22:15:47 +0800 Subject: [PATCH] =?UTF-8?q?P2002=20=E6=B6=88=E6=81=AF=E6=89=A9=E6=95=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R66118845 --- Luogu/P2002/P2002.cpp | 70 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Luogu/P2002/P2002.cpp diff --git a/Luogu/P2002/P2002.cpp b/Luogu/P2002/P2002.cpp new file mode 100644 index 00000000..1d583da9 --- /dev/null +++ b/Luogu/P2002/P2002.cpp @@ -0,0 +1,70 @@ +#include +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +const int N = 100005; + +std::vector g[N]; + +// Tarjan +int cnt, dfn[N], low[N]; +int scc_cnt, id[N]; +int din[N]; +std::stack st; +bool vis[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(); + id[v] = scc_cnt; + vis[v] = false; + } while (v != u); + } +} + +int main() { + int n, m; + cin >> n >> m; + for (int i = 1; i <= m; i++) { + int u, v; + cin >> u >> v; + g[u].push_back(v); + } + 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]]++; + } + } + } + int ans = 0; + for (int i = 1; i <= scc_cnt; i++) { + if (!din[i]) ans++; + } + cout << ans << endl; + return 0; +}