跳到正文

算法·理论

强连通分量 Tarjan算法

Caiwenyu约 1 分钟
原文
文章信息与版本

文章信息

收录
2026年8月1日
更新
2026年8月2日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
int dfn[N],dft,low[N];//low存储能到的 dfs序最小的点 
int co[N],cid;//标记强连通分量 
stack<int>stk;
int vis[N];//标记是否在栈内 
void tarjan(int u)
{
	dfn[u]=low[u]=++dft;
	stk.push(u);
	vis[u]=1;
	for(int v:e[u])
	{
		if(!dfn[v])//树边 
		{
			tarjan(v);
			low[u]=min(low[u],low[v]);
		}
 		else if(vis[v])//后向边或横叉边 
			low[u]=min(low[u],dfn[v]);
	}
	if(dfn[u]==low[u])
	{
		++cid;
		int x;
		while(1)
		{
			x=stk.top();
			stk.pop();
			vis[x]=0;
			co[x]=cid;
			ans[cid].push_back(x);
			if(x==u) break;
		}
	}
}
int main()
{
	for(int i=1;i<=n;i++)
		if(!dfn[i]) tarjan(i);
	return 0;
}
原文