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

    }

}
阅读更多
个人分类: 并查集
想对作者说点什么? 我来说一句

Business Objects XI 3.0白皮书.pdf

2008年04月23日 5.47MB 下载

没有更多推荐了,返回首页

不良信息举报

G: Xi and Bo

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭