团体天梯练习 L2-024 部落

发布时间 2023-04-18 23:51:21作者: Amαdeus

L2-024 部落

在一个社区里,每个人都有自己的小圈子,还可能同时属于很多不同的朋友圈。我们认为朋友的朋友都算在一个部落里,于是要请你统计一下,在一个给定社区中,到底有多少个互不相交的部落?并且检查任意两个人是否属于同一个部落。

输入格式:

输入在第一行给出一个正整数 \(N\)\(≤10^{4}\) ),是已知小圈子的个数。随后 \(N\) 行,每行按下列格式给出一个小圈子里的人:

\(K\) \(P[1]\) \(P[2]\)\(P[K]\)

其中 \(K\) 是小圈子里的人数, \(P[i]\)\(i=1,⋯,K\) )是小圈子里每个人的编号。这里所有人的编号从 \(1\) 开始连续编号,最大编号不会超过 \(10^{4}\)

之后一行给出一个非负整数 \(Q\)\(≤10^{4}\) ),是查询次数。随后 \(Q\) 行,每行给出一对被查询的人的编号。

输出格式:

首先在一行中输出这个社区的总人数、以及互不相交的部落的个数。随后对每一次查询,如果他们属于同一个部落,则在一行中输出 \(Y\) ,否则输出 \(N\)

输入样例:

4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7

输出样例:

10 2
Y
N


解题思路

很明显的并查集模板题。题中给出的是每个人关联的所有其他人的编号,不过编号是连续的,所以记录一下最大编号就行了(或者定义一个数组记录这个数字是否存在与集合中)。

/*   一切都是命运石之门的选择  El Psy Kongroo  */
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<double, double> pdd;
typedef pair<string, int> psi;
typedef __int128 int128;
#define PI acos(-1.0)
#define x first
#define y second
//int dx[4] = {1, -1, 0, 0};
//int dy[4] = {0, 0, 1, -1};
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;

const int N = 1e4 + 10;
int n, m, k, fa[N], s[N];
//m记录最大编号

void init(){
    for(int i = 1; i < N; i ++ ) fa[i] = i, s[i] = 1;
}

int find(int x){
    return fa[x] == x ? x : (fa[x] = find(fa[x]));
}

void Union(int x, int y){
    int fx = find(x), fy = find(y);
    if(fx == fy) return;
    fa[fx] = fy;
    s[fy] += s[fx];
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    init();
    while(n -- ){
        cin >> k;
        int a; cin >> a;
        m = max(m, a);
        k -- ;
        while(k -- ){
            int b; cin >> b;
            Union(a, b);
            m = max(m, b);
        }
    }

    int cnt = 0, sum = 0;
    for(int i = 1; i <= m; i ++ )
        if(fa[i] == i) cnt ++ , sum += s[i];
    cout << sum << ' ' << cnt << endl;

    int q; cin >> q;
    while(q -- ){
        int a, b; cin >> a >> b;
        int fx = find(a), fy = find(b);
        if(fx == fy) cout << "Y" << endl;
        else cout << "N" << endl;
    }

    return 0;
}