迷宫城堡
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 746 Accepted Submission(s): 282
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
//2009-05-04 14:31:28 Accepted 1269 62MS 1976K 1508 B C++ Xredman
#include <iostream>
#include <vector>
using namespace std;
const int N = 10002;
vector<int> xx[N];
vector<int> yy[N];
bool Visited[N];
int post[N], UFSet[N];
int n, m;
int cnt;
void dfs1(int y)
{
Visited[y] = true;
for(int i = 0;i < yy[y].size(); i++)
if(!Visited[yy[y][i]])
dfs1(yy[y][i]);
post[cnt++] = y;
}
void dfs2(int x)
{
Visited[x] = true;
UFSet[x] = cnt;
for(int i = 0; i < xx[x].size(); i++)
if(!Visited[xx[x][i]])
dfs2(xx[x][i]);
}
bool Kosaraju()
{
int i;
cnt = 0;
for(i = 1; i <= n; i++)
if(!Visited[i])
dfs1(i);
for(i = 1; i <= n; i++)
Visited[i] = false;
cnt = 1;
for(i = n - 1; i >= 0; i--)
if(!Visited[post[i]])
{
if(cnt == 2)
return false;
dfs2(post[i]);
cnt++;
}
return true;
}
int main()
{
int i;
int x, y;
while(scanf("%d%d", &n, &m)!= EOF)
{
if(n == 0 && m == 0)
break;
for(i = 1; i <= n; i++)
{
Visited[i] = false;
xx[i].clear();
yy[i].clear();
}
for(i = 0; i < m; i++)
{//input , create a graph
scanf("%d%d", &x, &y);
xx[x].push_back(y);
yy[y].push_back(x);
}
if(Kosaraju())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
const int N = 10002;
vector<int> xx[N];
vector<int> yy[N];
bool Visited[N];
int post[N], UFSet[N];
int n, m;
int cnt;
void dfs1(int y)
{
Visited[y] = true;
for(int i = 0;i < yy[y].size(); i++)
if(!Visited[yy[y][i]])
dfs1(yy[y][i]);
post[cnt++] = y;
}
void dfs2(int x)
{
Visited[x] = true;
UFSet[x] = cnt;
for(int i = 0; i < xx[x].size(); i++)
if(!Visited[xx[x][i]])
dfs2(xx[x][i]);
}
bool Kosaraju()
{
int i;
cnt = 0;
for(i = 1; i <= n; i++)
if(!Visited[i])
dfs1(i);
for(i = 1; i <= n; i++)
Visited[i] = false;
cnt = 1;
for(i = n - 1; i >= 0; i--)
if(!Visited[post[i]])
{
if(cnt == 2)
return false;
dfs2(post[i]);
cnt++;
}
return true;
}
int main()
{
int i;
int x, y;
while(scanf("%d%d", &n, &m)!= EOF)
{
if(n == 0 && m == 0)
break;
for(i = 1; i <= n; i++)
{
Visited[i] = false;
xx[i].clear();
yy[i].clear();
}
for(i = 0; i < m; i++)
{//input , create a graph
scanf("%d%d", &x, &y);
xx[x].push_back(y);
yy[y].push_back(x);
}
if(Kosaraju())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}