迷宫城堡 HDU - 1269 Tarjian判强联通

题目链接:HDU-1269

主要思路:

本题为Tarjian模板题,最后判强连通块有没有大于1,若大于1则输出NO小于等于1则输出YES。

若还不懂Tarjian的人可以去百度搜索一下。

附上代码与解说:

#include<cstdio>
#include<cstring>
#define M 10005
struct E {
	int nx,to;
} edge[M*10];
int tot,head[M];
void Addedge(int a,int b) {
	edge[++tot].to=b;
	edge[tot].nx=head[a];
	head[a]=tot;
}
void Init() {
	tot=0;
	memset(head,0,sizeof(head));
}
int ID[M],T,low[M];
int stack[M],top,Belong[M],Bcnt;//Bcnt为强联通块编号,Belong[i]为i的强联通编号。 
void tarjian(int now) {
	ID[now]=low[now]=++T;
	stack[++top]=now;
	for(int i=head[now]; i; i=edge[i].nx) {
		int nxt=edge[i].to;
		if(!ID[nxt]) {//若下一个结点还没被枚举到 
			tarjian(nxt);
			if(low[now]>low[nxt])low[now]=low[nxt];//如果他子树内的结点low值比他小 
		} else {
			if(!Belong[nxt]&&ID[nxt]<low[now])low[now]=ID[nxt];//若这条边为返祖边,之一是将比下一个结点的dfs序而不是low值 
		}
	}
	int nxt;
	if(ID[now]==low[now]) {
		Bcnt++;
		do {
			nxt=stack[top--];
			Belong[nxt]=Bcnt;
		} while(nxt!=now);
	}
}
void solve(int n) {
	for(int i=1;i<=n;i++)ID[i]=Belong[i]=0;//Belong数组可以直接代替instack数组,故要清空 
	T=top=Bcnt=0;
	for(int i=1; i<=n; i++)if(!ID[i])tarjian(i);
}
int main() {
	int n,m;
	while(~scanf("%d%d",&n,&m)) {
		if(n==0&&m==0)return 0;
		Init();
		while(m--) {
			int a,b;
			scanf("%d%d",&a,&b);
			Addedge(a,b);
		}
		solve(n);
		if(Bcnt<=1)puts("Yes");
		else puts("No");
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值