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
为了训练小希的方向感,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<stdio.h>
#include<string.h>
#define N 10005
#define M 100005
struct Edge
{
int v;
int next;
};
Edge edge[M];//边的集合
int node[N];//顶点集合
int instack[N];//标记是否在stack中
int stack[N];
int Belong[N];//各顶点属于哪个强连通分量
int DFN[N];//节点u搜索的序号(时间戳)
int LOW[N];//u或u的子树能够追溯到的最早的栈中节点的序号(时间戳)
int n, m;//n:点的个数;m:边的条数
int cnt_edge;//边的计数器
int Index;//序号(时间戳)
int top;
int Bcnt;//有多少个强连通分量
void init()
{
memset(node,-1,sizeof(node));
cnt_edge=0;
top=Bcnt=Index=0;
memset(DFN,0,sizeof(DFN));
memset(instack,0,sizeof(instack));
memset(LOW,0,sizeof(LOW));
}
void add_edge(int u, int v)//邻接表存储
{
edge[cnt_edge].next =node[u];
edge[cnt_edge].v =v;
node[u]=cnt_edge++;
}
void tarjan(int u)
{
int i,j;
int v;
DFN[u]=LOW[u]=++Index;
instack[u]=true;
stack[++top]=u;
for(i=node[u];i!=-1;i=edge[i].next)
{
v=edge[i].v;
if (!DFN[v])//如果点v没被访问
{
tarjan(v);
if (LOW[v]<LOW[u])
LOW[u]=LOW[v];
}
else//如果点v已经被访问过
if (instack[v] && DFN[v]<LOW[u])
LOW[u]=DFN[v];
}
if (DFN[u]==LOW[u])
{
Bcnt++;
do
{
j=stack[top];
top--;
instack[j]=false;
Belong[j]=Bcnt;
}
while (j!=u);
}
}
void solve()
{
int i;
for (i=1;i<=n;i++)
if (!DFN[i])
tarjan(i);
}
int main()
{
//freopen("b.txt","r",stdin);
int i,a,b;
while(scanf("%d %d",&n,&m)==2&&m+n)
{
init();
for(i=1;i<=m;i++)
{
scanf("%d %d",&a,&b);
add_edge(a,b);
}
solve();
if(Bcnt==1) printf("Yes\n");
else printf("No\n");
}
return 0;
}