迷宫城堡 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");
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35320178/article/details/81452203