HDU1269 迷宫城堡(tarjan判断强连通)

裸的判断强连通,如果整个图中只有一个强连通分量,就“Yes”,否则“No”

tarjan的代码:

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;

const int N = 10001;

struct Edge{
	int s,e,next;
}edge[10*N];

int n,m,e_num,vis_num,cnt,head[N],instack[N],low[N],tim[N];

void AddEdge(int a,int b){
	edge[e_num].s=a; edge[e_num].e=b; edge[e_num].next=head[a]; head[a]=e_num++;
}

void getmap(){
	int a,b;
	memset(instack,0,sizeof(instack));
	memset(low,0,sizeof(low));
	memset(tim,-1,sizeof(tim));

	e_num=0;
	memset(head,-1,sizeof(head));
	while(m--){
		scanf("%d%d",&a,&b);
		AddEdge(a,b);
	}
}

stack <int> st;
void tarjan(int x){
	int j;
	tim[x]=low[x]=++vis_num;
	instack[x]=1;
	st.push(x);
	for(j=head[x];j!=-1;j=edge[j].next){
		int u=edge[j].e;
		if(tim[u]==-1){
			tarjan(u);
			if(low[x]>low[u])low[x]=low[u];
		}
		else if(instack[u] && low[x]>tim[u])low[x]=tim[u];
	}
	if(low[x]==tim[x]){
		cnt++;
		do{
			j=st.top();
			st.pop();
			instack[j]=0;
		}while(j!=x);
	}
}

void solve(){
	int i;
	vis_num=cnt=0;
	for(i=1;i<=n;i++){
		if(tim[i]==-1)tarjan(i);
	}
	if(cnt==1)printf("Yes\n");
	else printf("No\n");
}
int main()
{
	while(scanf("%d%d",&n,&m),n+m)
	{
		getmap();
		solve();
	}
	return 0;
}


你可能感兴趣的:(struct)