HDU 1269 迷宫城堡(裸强连通分量,3级)


迷宫城堡

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4676    Accepted Submission(s): 2043


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
 

Recommend
lxj

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int mm=2e5+9;
int head[mm],next[mm],ver[mm],e_to[mm],edge;
int stack[mm],low[mm],dfn[mm],dex,top,cnt;
bool vis[mm];
int n,m;
void add(int u,int v)
{ ver[edge]=v;next[edge]=head[u];head[u]=edge++;
}
void tarjan(int u)
{ int v;
  dfn[u]=low[u]=++dex;
  vis[u]=1;
  if(top+6>mm)return;
  stack[top++]=u;
  for(int i=head[u];~i;i=next[i])
  {v=ver[i];
   if(!dfn[v])
   {tarjan(v);
    if(low[v]<low[u])low[u]=low[v];
   }
   else if(vis[v]&&dfn[v]<low[u])low[u]=dfn[v];
  }
  if(dfn[u]==low[u])
   {
    ++cnt;
    do
    {v=stack[--top];
     vis[v]=0;
     e_to[v]=cnt;
    }while(v^u);
   }
}
void solve()
{
 top=dex=cnt=0;
 memset(dfn,0,sizeof(dfn));
 memset(vis,0,sizeof(vis));
 for(int i=1;i<=n;++i)
 if(!dfn[i])tarjan(i);
}
int main()
{ int a,b;
  while(~scanf("%d%d",&n,&m))
  {if(n==0&&m==0)break;
   edge=0;
   memset(head,-1,sizeof(head));
   for(int i=0;i<m;++i)
   {
    scanf("%d%d",&a,&b);add(a,b);
   }
   solve();
   int z=e_to[1];bool flag=1;
   ///for(int i=1;i<=n;++i)
   ///cout<<e_to[i]<<" ";puts("");
   for(int i=2;i<=n;++i)
   if(z^e_to[i])
   flag=0;
   if(flag&&m||n<2)cout<<"Yes\n";
   else cout<<"No\n";
  }
  return 0;
}





posted @ 2013-05-31 10:42  剑不飞  阅读(176)  评论(0编辑  收藏  举报