专栏文章
Tarjan
算法·理论参与者 1已保存评论 0
文章操作
快速查看文章及其快照的属性,并进行相关操作。
- 当前评论
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @minjnry5
- 此快照首次捕获于
- 2025/12/02 03:30 3 个月前
- 此快照最后确认于
- 2025/12/02 03:30 3 个月前
CPP
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+5;
const int M=5e4+5;
int n,m,cnt,num,top,col;
int dfn[N],low[N],st[N],color[N];
int head[M],to[M],nxt[M];
void add(int u,int v)
{
cnt++;
to[cnt]=v;
nxt[cnt]=head[u];
head[u]=cnt;
}
void tarjan(int u)
{
dfn[u]=low[u]=++num;
st[++top]=u;
for(int i=head[u];i;i=nxt[i])
{
int v=to[i];
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(!color[v]) low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
color[u]=++col;
while(st[top]!=u) color[st[top--]]=col;
--top;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1;i<=m;++i)
{
int u,v;
cin>>u>>v;
add(u,v);
}
for(int i=1;i<=n;++i)
if(!dfn[i]) tarjan(i);
for(int i=1;i<=n;++i) cout<<color[i]<<" ";
return 0;
}
相关推荐
评论
共 0 条评论,欢迎与作者交流。
正在加载评论...