您的位置:首页 > 其它

HDU 1269 迷宫城堡

2016-07-05 23:14 253 查看


迷宫城堡


Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)


Total Submission(s) : 19   Accepted Submission(s) : 8


Font: Times New Roman | Verdana | Georgia


Font Size: ← →


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


<pre name="code" class="cpp">#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;

const int N = 10005;

vector<int> adj
, t_adj
;
bool visit
;
int n, m, cnt;

bool dfs(int rt, vector<int> *graph)
{
stack<int> st;
st.push(rt);
visit[rt] = true;
cnt = 0;

while (!st.empty())
{
int u = st.top();
++cnt;
st.pop();

for (int i = 0; i < graph[u].size(); ++i)
{
if (visit[graph[u][i]])continue;
st.push(graph[u][i]);
visit[graph[u][i]] = true;
}

}
if (cnt == n)return true;
return false;
}

void transform()
{
for (int i = 1; i <= n; ++i)
{
for (unsigned j = 0; j < adj[i].size(); ++j)
{
t_adj[adj[i][j]].push_back(i);
}
}
}

bool kosaraju()
{
memset(visit, 0, sizeof(visit));

bool ret = dfs(1, adj);
if (!ret)return false;

transform();
memset(visit, 0, sizeof(visit));

ret = dfs(1, t_adj);
if (ret)return true;
return false;
}

int main()
{
int a, b;

while (scanf("%d %d", &n, &m) != EOF && (m + n))
{
for (int i = 0; i < m; ++i)
{
scanf("%d %d", &a, &b);
adj[a].push_back(b);
}

if (kosaraju())
{
printf("Yes\n");
}
else
{
printf("No\n");
}

for (int i = 1; i <= n; ++i)
{
adj[i].clear();
t_adj[i].clear();
}
}
return 0;
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: