CSES-1683 Planets and Kingdoms
Planets and Kingdoms
找出所有的点所属的强连通块编号
tarjan 模板
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
const int maxn = 1e5 + 10;
vector<int>gra[maxn];
int vis[maxn], scc[maxn], cnt_scc = 0;
int dfn[maxn], low[maxn], tp = 0;
stack<int>st;
void tarjan(int now)
{
vis[now] = 1;
st.push(now);
dfn[now] = low[now] = ++tp;
for(int nex : gra[now])
{
if(dfn[nex] == 0)
{
tarjan(nex);
low[now] = min(low[now], low[nex]);
}
else if(vis[nex])
low[now] = min(low[nex], low[now]);
}
if(low[now] == dfn[now])
{
cnt_scc++;
while(st.top() != now)
{
int x = st.top();
vis[x] = 0;
st.pop();
scc[x] = cnt_scc;
}
vis[now] = 0;
st.pop();
scc[now] = cnt_scc;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for(int i=0; i<m; i++)
{
int a, b;
cin >> a >> b;
gra[a].push_back(b);
}
for(int i=1; i<=n; i++)
if(dfn[i] == 0) tarjan(i);
cout << cnt_scc << endl;
for(int i=1; i<=n; i++)
{
if(i != 1) cout << " ";
cout << scc[i];
}
cout << endl;
return 0;
}