迷宫城堡
为了训练小希的方向感,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 0Sample Output
Yes No
模板题
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<vector>
#include<stack>
#include<list>
#include<map>
#include<set>
using namespace std;
const int maxn = 100000+5;
int Laxt[maxn],Next[maxn],To[maxn],cnt,n,m,ans;
int times,dfn[maxn],low[maxn],scc[maxn],scc_cnt;
int stc[maxn],top,instc[maxn];
void add(int u,int v)
{
Next[++cnt]=Laxt[u];
Laxt[u]=cnt;
To[cnt]=v;
}
void init()
{
top=cnt=scc_cnt=ans=0;
memset(Laxt,0,sizeof(Laxt));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(scc,0,sizeof(scc));
memset(stc,0,sizeof(stc));
memset(instc,0,sizeof(instc));
}
int dfs(int u)
{
dfn[u]=low[u]=++times;
stc[++top]=u;
instc[u]=1;
for(int i=Laxt[u]; i; i=Next[i])
{
int v=To[i];
if(!dfn[v])
{
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(instc[v])
{
low[u]=min(low[u],low[v]);
}
}
if(dfn[u]==low[u])
{
scc_cnt++;
while(true)
{
int x=stc[top--];
scc[x]=scc_cnt;
instc[x]=0;
if(x==u) break;
}
}
}
void tarjan()
{
int i;
for(i=1; i<=n; i++)
if(!dfn[i]) dfs(i);
if(scc_cnt==1) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
int main()
{
while(scanf("%d %d",&n,&m),n+m)
{
init();
int a,b;
for(int i=1; i<=m; i++)
{
scanf("%d %d",&a,&b);
add(a,b);
}
tarjan();
}
}