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
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<iostream> #define N 1000005 using namespace std; int dfn[N],low[N],head[N],sk[N],scc[N],cnt,sccnum,index,tp; //scc[]值相同的,梭点后属于同一个点,sccnum表示缩点后有几个点 //dfn[x]表示x这个点dfs到的时间(深浅) //low[x]此点及其后代指出去的边能返回的最浅的点的时间戳(dfn) struct edge{ int next,to,w; }ed[N]; void add(int u,int v,int w){ ed[cnt].w = w; ed[cnt].to = v; ed[cnt].next = head[u]; head[u] = cnt++; } void tarjan(int root)//head初始值为-1时,用~i; head 初始值为0时用i { dfn[root]=low[root]=++index; sk[++tp]=root; int i; for(i=head[root];~i;i=ed[i].next) { int v=ed[i].to; if(!dfn[v]) { tarjan(v); low[root]=min(low[root],low[v]); } else if(!scc[v]) { low[root]=min(low[root],dfn[v]); } } if(low[root]==dfn[root]) { sccnum++; for(;;) { int x=sk[tp--]; scc[x]=sccnum; if(x==root)break; } } } int main(){ int n,m; while(scanf("%d%d",&n,&m)!=EOF){ if(!n&&!m)break; memset(dfn,0,sizeof(dfn)); memset(low,0,sizeof(low)); memset(scc,0,sizeof(scc)); memset(head,-1,sizeof(head)); sccnum=0; index=0; tp=0; cnt=0; for(int i=1;i<=m;i++){ int u,v; scanf("%d%d",&u,&v); add(u,v,1); } for(int i=1;i<=n;i++){ if(!dfn[i])tarjan(i); } if(sccnum>1)printf("No\n"); else printf("Yes\n"); } return 0; }