lkrkerry @ 2024-06-08 10:05:26
#include <bits/stdc++.h>
using namespace std;
unordered_map<int, vector<int>> graph;
int tc = 0;
stack<int> st;
vector<int> vis;
vector<int> dfn;
vector<int> low;
vector<int> cur;
map<int, set<int>> ans;
void tarjan(int u)
{
low[u] = dfn[u] = ++tc;
st.push(u);
cur[u] = 1;
for (auto x : graph[u])
{
if (!dfn[x])
{
// same as dfs
tarjan(x);
low[u] = min(low[u], low[x]);
}
else if (cur[x])
{
// in and searched, son
low[u] = min(low[u], dfn[x]); // notice dfn
}
}
if (low[u] == dfn[u])
{
// found strong!
set<int> tmp;
int t = 0x3f3f3f3f;
int x;
do
{
// pop all until u!
x = st.top();
st.pop();
tmp.insert(x);
cur[x] = 0;
t = min(t, x);
} while (x != u);
ans[t] = tmp;
}
}
int main()
{
cin.tie(0)->sync_with_stdio(0);
int n, m;
cin >> n >> m;
vis.resize(n + 1), dfn.resize(n + 1), low.resize(n + 1), cur.resize(n + 1);
for (int i = 1; i <= m; i++)
{
int u, v;
cin >> u >> v;
graph[u].push_back(v);
}
tarjan(1);
cout << ans.size() << "\n";
for (auto x : ans)
{
for (auto y : x.second)
{
cout << y << " ";
}
cout << "\n";
}
return 0;
}
by happy_zero @ 2024-06-08 10:37:26
@lkrkerry 图不一定联通,所以得进行多次 tarjan
:
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
by lkrkerry @ 2024-06-08 11:01:49
@happy_zero 已过,谢谢