PTA路径判断

给定一个有N个顶点和E条边的无向图,请判断给定的两个顶点之间是否有路径存在。
假设顶点从0到N−1编号。

输入格式:

输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。

随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。

最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。

输出格式:

如果i和j之间存在路径,则输出"There is a path between i and j.",

否则输出"There is no path between i and j."。

输入样例1:

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

输出样例1:

There is a path between 0 and 3.

输入样例2:

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

输出样例2:

There is no path between 0 and 6.

代码如下:

#include<bits/stdc++.h>
using namespace std;
int fa[10005];
void init(int n){
	for(int i = 0;i<n;i++){
		fa[i] = i;
	}
}
int find(int x){
	if(fa[x]==x){
		return x;
	}else{
		fa[x] = find(fa[x]);
		return fa[x];
	}
}
void merge(int x,int y){
	int a = find(x);
	int b = find(y);
	if(a!=b){
		fa[a] = b;
	}
}

int main(){
	int n,e;
	cin>>n>>e;
	init(n);
	int a,b;
	for(int i = 0;i<e;i++){
		cin>>a>>b;
		merge(a,b);
	}
	int x,y;
	cin>>x>>y;
	if(find(x)==find(y)){
		cout<<"There is a path between "<<x<<" and "<<y<<".";
	}else{
		cout<<"There is no path between "<<x<<" and "<<y<<".";
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值