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

简单说一下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;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值