有向图tarjan

进行tarjan缩点后的图的拓扑序与原图的连通分量编号的倒序对应

scc|tarjan Code

#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
const int maxm=1000010;
int n,m,ans;
int h[maxn],to[maxm],nxt[maxm],tot,cnt;
int dfn[maxn],low[maxn],num;
int zhan[maxm],top,scc_num[maxn],scc_size[maxn];
bool in_zhan[maxn];
vector<int> scc[maxn];
void add(int x,int y)
{
	tot++;
	to[tot]=y;
	nxt[tot]=h[x];
	h[x]=tot;
}
void tarjan(int x)
{
	int y=0;
	num++;
	dfn[x]=low[x]=num;
	zhan[++top]=x;
	in_zhan[x]=true;
	for (int i=h[x];i;i=nxt[i])
	{
		y=to[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (in_zhan[y])
		{
			low[x]=min(low[x],dfn[y]);
		}
	}
	if (dfn[x] == low[x])
	{
		cnt++;
		do
		{
			y=zhan[top];
			top--;
			in_zhan[y]=false;
			scc_num[y]=cnt;
			scc[cnt].push_back(y);
			++scc_size[cnt];
		} while (x!=y);
	}
}
int main()
{
	int x,y;
	cin >> n >> m;
	for (int i=1;i<=m;i++)
	{
		cin >> x >> y;
		add(x,y);
	}
	for (int i=1;i<=n;i++) if (!dfn[i]) tarjan(i);
	for (int i=1;i<=cnt;i++) if (scc_size[i]>1) ans++;
	cout << ans << endl;
	return 0;
}

tarjan缩点 Code

#include <bits/stdc++.h>
using namespace std;
const int maxn = 500010;
const int maxm = 500010;
int n,m;
int h[maxn],to[maxm],nxt[maxm],tot;	
int dfn[maxn],low[maxn],num; 
int stk[maxn],top,ins[maxn],cnt,c[maxn];
vector<int> scc[maxn];
int hc[maxn],toc[maxm],nxtc[maxm],totc;

void addedge(int x,int y)
{
	to[++tot] = y;
	nxt[tot] = h[x];
	h[x] = tot;
}

void addedge_c(int x,int y)
{
	toc[++totc] = y;
	nxtc[totc] = hc[x];
	hc[x] = totc;
}

void tarjan(int x)
{
	int y = 0;
	dfn[x] = low[x] = ++num;
	stk[++top] = x;
	ins[x] = 1;
	
	for(int i=h[x]; i; i=nxt[i])
	{
		y = to[i];
		if(!dfn[y])
		{
			tarjan(y);
			
			low[x] = min(low[x], low[y]);
		}		
		else if(ins[y])
		{
			low[x] = min(low[x], dfn[y]);
		}
	}
	
	if(dfn[x] == low[x])
	{
		cnt++;
		do
		{
			y = stk[top--];
			ins[y] = 0;
			c[y] = cnt;
			scc[cnt].push_back(y);
		}while(x != y);
	}
}

int main()
{	 
	int x=0,y=0;
	cin >> n >> m;
	for(int i=1; i<=m; i++)
	{
		cin >> x >> y;
		addedge(x, y);
	}
	//tarjan求scc模板
	for(int i=1; i<=n; i++)
	{
		if(!dfn[i]) tarjan(i);
	}
	//缩点,建新图
	for(int x=1; x<=n; x++)
	{
		for(int i=h[x]; i; i=nxt[i])
		{
			y = to[i];
			if(c[x] == c[y]) continue;
			addedge_c(c[x], c[y]);
		}
	}
	return 0;
}
posted @ 2026-03-24 11:45  msjing  阅读(12)  评论(0)    收藏  举报