Problem Description
为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M<=100000),每个通道都是单向的,就是说若称某通道连通了A房间和B房间,只说明可以通过这个通道由A房间到达B房间,但并不说明通过它可以由B房间到达A房间。Gardon需要请你写个程序确认一下是否任意两个房间都是相互连通的,即:对于任意的i和j,至少存在一条路径可以从房间i到房间j,也存在一条路径可以从房间j到房间i。
Input
输入包含多组数据,输入的第一行有两个数:N和M,接下来的M行每行有两个数a和b,表示了一条通道可以从A房间来到B房间。文件最后以两个0结束。
Output
对于输入的每组数据,如果任意两个房间都是相互连接的,输出”Yes”,否则输出”No”。
Sample Input
3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0
Sample Output
Yes
No
Author
Gardon
Source
HDU 2006-4 Programming Contest
Solution
这题是一道经典的Tarjan题,直接求强连通分量!
如果整个图的强连通分量的数量为1,那么说明这个图是强连通的。
Code
#include<cstdio>
#include<cstring>
#define P(x) putchar(x)
using namespace std;
const int N=10001;
int tot,now,top,num,n,m;
int first[N],next[N*10],en[N*10];
int dfn[N],low[N],stack[N];
bool bz[N];
inline int read()
{
int data=0; char ch=0;
while(ch<'0' || ch>'9') ch=getchar();
while(ch>='0' && ch<='9') data=data*10+ch-'0',ch=getchar();
return data;
}
inline void tarjan(int x)
{
if(num>1) return;
dfn[x]=low[x]=++now;
bz[stack[++top]=x]=true;
for(int i=first[x];i;i=next[i])
if(!dfn[en[i]])
{
tarjan(en[i]);
if(low[en[i]]<low[x]) low[x]=low[en[i]];
}else
if(bz[en[i]] && dfn[en[i]]<low[x]) low[x]=dfn[en[i]];
if(dfn[x]==low[x])
{
do
{
bz[stack[top--]]=false;
}while(stack[top+1]!=x);
num++;
}
}
int main()
{
while(true)
{
n=read(),m=read();
if(!n && !m) return 0;
memset(first,0,sizeof(first));
memset(dfn,0,sizeof(dfn));
now=tot=top=num=0;
for(int i=1;i<=m;i++)
{
int x=read(),y=read();
next[++tot]=first[x];
first[x]=tot;
en[tot]=y;
}
for(int i=1;i<=n;i++)
if(!dfn[i]) tarjan(i);
if(num==1) P('Y'),P('e'),P('s'); else P('N'),P('o');
P('\n');
}
}