当前位置: 移动技术网 > 移动技术>移动开发>Android > [HDU-1269] SCC tarjan求强连通分量模板题

[HDU-1269] SCC tarjan求强连通分量模板题

2020年07月09日  | 移动技术网移动技术  | 我要评论

简单说一下tarjan 求SCC的思路:

dfn[i]:点i的时间戳

low[i]:点i通过i的子树点可达(且有用的)点中时间戳最小的点,

x -> y 是有用的: 

1:x经过横叉边到达y,且从y出发存在一条路径z(z是x的祖先节点);这样x->z->y 形成一个环路

2:x经过后向边到达其祖先y,

每次经过点x把它加入到栈中。

x回溯时判断dfn[x]是否等于low[x].

若等于,则把栈中元素弹出到x,与x构成SCC(因为此时其他点一定不会与x构成SCC)

 

#include <cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
typedef long long ll;
#define ls (o<<1)
#define rs (o<<1|1)
#define pb push_back
const double PI= acos(-1.0);
const int M = 1e5+7;
const int N = 1e5+7;
int head[N],cnt=1;

struct EDGE{int to,nxt,w;}ee[M*2];
void add(int x,int y,int w){ee[++cnt].nxt=head[x],ee[cnt].w=w,ee[cnt].to=y,head[x]=cnt;}

int n,m,num,top,ct;
int sk[N],ins[N],c[N];
int dfn[N],low[N];
vector<int>scc[N];
void tarjan(int x)
{
	dfn[x]=low[x]=++num;
	sk[++top]=x,ins[x]=1;
	//cout<<x<<" -  "<<endl;
	for(int i=head[x];i;i=ee[i].nxt)
	{
		int y=ee[i].to;
		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])
	{
		ct++;int y;
		do{
			y=sk[top--],ins[y]=0;
			c[y]=ct,scc[ct].pb(y);
		}while(x!=y);
	}
}
void init(){
	cnt=1,memset(head,0,sizeof(head));
	memset(dfn,0,sizeof(dfn));
	num=ct=0;
}
int main()
{
	ios::sync_with_stdio(false);
  	cin.tie(0);
  	while(1)
	{
		cin>>n>>m;
		if(n==0)break;
		init();
		for(int i=1;i<=m;i++)
		{
			int x,y;
			cin>>x>>y;
			add(x,y,1);
		}
		for(int i=1;i<=n;i++)
			if(!dfn[i])tarjan(i);
		if(ct==1)cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}
	return 0;
}

 

本文地址:https://blog.csdn.net/bjfu170203101/article/details/107208862

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网