1004: Xi and Bo

Description

Bo has been in Changsha for four years. However he spends most of his time staying his small dormitory. One day he decides to get out of the dormitory and see the beautiful city. So he asks to Xi to know whether he can get to another bus station from a bus station. Xi is not a good man because he doesn't tell Bo directly. He tells to Bo about some buses' routes. Now Bo turns to you and he hopes you to tell him whether he can get to another bus station from a bus station directly according to the Xi's information.

Input

The first line of the input contains a single integer T (0<T<30) which is the number of test cases. For each test case, the first contains two different numbers representing the starting station and the ending station that Bo asks. The second line is the number n (0<n<=50) of buses' routes which Xi tells. For each of the following n lines, the first number m (2<=m<= 100) which stands for the number of bus station in the bus' route. The remaining m numbers represents the m bus station. All of the bus stations are represented by a number, which is between 0 and 100.So you can think that there are only 100 bus stations in Changsha.

Output

For each test case, output the "Yes" if Bo can get to the ending station from the starting station by taking some of buses which Xi tells. Otherwise output "No". One line per each case. Quotes should not be included.

Sample Input

3
0 3
3
3 1 2 3
3 4 5 6
3 1 5 6
0 4
2
3 0 2 3
2 2 4
3 2
1
4 2 1 0 3

Sample Output

No
Yes
Yes

题目大意

有n条公交线路,每条线路连接m个公交站。问能否从一个公交站到另一个公交站。

解题思路

我觉得这是并查集问题,但是我没想好怎么做,用并查集效率会很高但是。显然我不能熟练运用。所以我用一个本办法,用邻接矩阵来存,然后dfs遍历看看能否找到路。

AC Code

#include<iostream>
#include<string.h>
using namespace std;
const int MAXN=1e2+10;
int a[MAXN];
int map[MAXN][MAXN];
bool visited[MAXN];
void setMap(int a[], int size){
	for(int i=0; i<size; ++i){
		for(int j=0; j<size; ++j){
			map[a[i]][a[j]]=1;
		}
	}
}

bool dfs(int x, int y){
	if(map[x][y]) return 1;
	visited[x]=1;
	for(int j=0; j<MAXN; ++j){
		if(!visited[j] && map[x][j]==1) 
			return dfs(j,y);
	}
	return 0;
}
int main(){
	//freopen("C:\\Users\\Ambition\\Desktop\\in.txt","r",stdin);
	int t;
	scanf("%d", &t);
	while(t--){
		memset(map,0,sizeof(map));
		memset(visited,0,sizeof(visited));
		int start, end, n, m;
		scanf("%d %d %d", &start, &end, &n);
		for(int i=0; i<n; ++i){
			scanf("%d", &m);
			for(int j=0; j<m; ++j){
				scanf("%d", &a[j]);
			}
			setMap(a,m);
		}
		if(dfs(start,end))
			printf("Yes\n");
		else 
			printf("No\n");
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值