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");

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值