求助:如何把Tarjan缩点后建立新图?
查看原帖
求助:如何把Tarjan缩点后建立新图?
545986
Jerrycyx楼主2022/5/8 21:30

RT\texttt{RT},代码如下:

#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>

#define N 10005
#define M 100005

using namespace std;

int n,m;

struct Allan{
	int from,to;
	int next;
}edge[M];
int tot=0;
int head[M];

int value[N];

int dfn[N];
int low[N];
stack<int>sta;
int num=0;
int c[N];
int cnt=0;
int sum[N];

void add(int from,int to)
{
	tot++;
	edge[tot].from=from;
	edge[tot].to=to;
	edge[tot].next=head[from];
	head[x]=tot;
	return;
}

void Tarjan(int x)
{
	low[x]=dfn[x]=++num;
	sta.push(x);
	for(int i=head[x];i;i=edge[i].next)
	{
		int to=edge[i].to;
		if(dfn[to]==0)
		{
			Tarjan(to);
			low[x]=min(low[x],low(to));
		}
		else if(c[to]==0)
			low[x]=min(low[x],dfn[to]);
	}
	if(dfn[x]==low[x])
	{
		while(sta.top()!=x)
		{
			cnt++;
			c[sta.top()]=cnt;
			sta.pop();
		}
		sta.pop();
	}
	return;
}



int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&value[i]);
	for(int i=1;i<=m;i++)
	{
		int from,to;
		scanf("%d%d",&from,&to);
		add(from,to);
	}
	
	for(int i=1;i<=n;i++)
		if(dfn[i]==0) Tarjan(i);
	
	return 0;
}
2022/5/8 21:30
加载中...