本文主要是介绍G: 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.
并查集:
查询起始站与终点站是否在同一个集合里面。
注意join是根指向根。开始就搞错了
find之后可以指向根节点
#include <iostream>
#include <cmath>
#include<set>
#include<string.h>
#include <type_traits>
#include <queue>
#include <tuple>
#include<tuple>#define inf 0x3f3f3f3f
#define LL long long
#define mod 100000007
using namespace std;int head[104];void inti() {for (int i = 0; i < 104; i++) {head[i] = i;}
}int find(int a){//找到根节点,并指向他int a2=a;while(head[a]!=a){a=head[a];}head[a2]=a;return a;
}void join(int a, int b) {int ra=find(a);int rb=find(b);if (ra!=rb) {//这里或许不用这么写,因为find后,该节点就会指向根节点head[rb] = ra;}
}int main() {int st, et,T;scanf("%d",&T);while (T--) {inti();scanf("%d%d", &st, &et);int n;scanf("%d", &n);for (int i = 0; i < n; i++) {int m, st1;scanf("%d", &m);scanf("%d", &st1);m--;while (m--) {int station;scanf("%d", &station);join(st1, station);}}if (find(st) == find(et))puts("Yes");else puts("No");}}
这篇关于G: Xi and Bo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!