[Swust OJ 85]--单向公路(BFS)

时间:2023-03-08 17:06:32

题目链接:http://acm.swust.edu.cn/problem/0085/

Time limit(ms): 5000      Memory limit(kb): 65535
Description

某个地区有许多城镇,但并不是每个城镇都跟其他城镇有公路连接,且有公路的并不都能双向行驶。现在我们把这些城镇间的公路分布及允许的行驶方向告诉你,你需要编程解决通过公路是否可以从一个城镇到达另一个城镇。(我们规定,城镇自己跟自己可互相到达,即A可到达A).

Input

第一行只有一个数N,下面将跟着2N行数据. 在前N行数据中,对于每行数据,最开头一个数字number,表明这一行总共有number个数,number的下一个数为i,代表编号为i的那个城镇.这行余下的就是跟i有公路连接的城镇的(编号)名单,且只能从城镇i驶向其他城镇。如 4 1 2 3,表明:此行有4个数,跟城镇1有公路连接的城镇是编号为2和3的城镇.是从1连到2 和3 ,不能从2 和3 连到1. 在后N行数据中,每行由两个数字组成a,b(表示城镇的编号). 对于每个输入的数有如下关系 0 <= input_number <= 1000 .

Output

对于输入数据中的每个a,b,判断是否可以从城镇a通过公路到达城镇b,如果可以,输出Yes;否则输出No.

Sample Input

3
4 1 2 3
3 4 5
3 5 8
1 2
1 8
4 8
Sample Output
Yes
No
Yes
解题思路:处理好数据后直接bfs~~~
代码如下:
 #include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
int mpt[][], vis[];
int bfs(int x, int y, int n){
queue<int> Q;
Q.push(x);
while (!Q.empty()){
int now = Q.front();
Q.pop();
if (now == y) return ;
for (int i = ; i < n; i++){
if (!vis[i] && mpt[now][i]){
vis[i] = ;
Q.push(i);
}
}
}
return ;
}
int main(){
int n, t, x, y, i, j, maxn = -;
cin >> t;
for (i = ; i < t; i++){
cin >> n >> x;
for (j = ; j < n - ; j++){
cin >> y;
mpt[x][y] = ;
maxn = max(maxn, max(x, y) + );//找出出现的点的最大值+1,避免大范围搜索不必要的点
}
}
for (i = ; i < t; i++){
memset(vis, , sizeof(vis));
cin >> x >> y;
cout << (bfs(x, y, maxn) ? "Yes\n" : "No\n");
}
return ;
}

以前有个代码,个人感觉没问题,但是一直Rutime Error,有大神路过给个原因吧~~~

代码如下:

 #include <stdio.h>
#include <string.h>
#define maxn 10001
int map[maxn][maxn], max;
int dfs(int star, int next)
{
int i, flag, vis[maxn];
memset(vis, , sizeof(vis));
vis[star] = ;
if (map[star][next] == )
return ;
for (i = , flag = ; i <= max&&!flag; i++)
{
if (vis[i] == && map[star][i] == )
{
vis[i] = ;
flag = dfs(i, next);
vis[i] = ;
}
}
return flag;
}
int main()
{
int i, j, m, n;
int star, next;
scanf("%d", &n);
memset(map, , sizeof(map));
for (i = ; i<maxn; i++)
map[i][i] = ;
max = ;
for (i = ; i <= n; i++)
{
scanf("%d%d", &m, &star);
if (star> max)
max = star;
for (j = ; j <= m - ; j++)
{
scanf("%d", &next);
if (next > max)
max = next;
map[star][next] = ;
}
}
for (i = ; i <= n; i++)
{
scanf("%d%d", &star, &next);
if (dfs(star, next))
printf("YES\n");
else
printf("NO\n");
}
return ;
}