L2-024 部落 分數 25

Frodnx發表於2024-08-29

基礎款並查集練習題

// 13'11"
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int p[N], f[N];
void init()
{
    for(int i = 1; i <= N; ++ i)
        p[i] = i;
}
int find(int x)
{
    if(x != p[x]) p[x] = find(p[x]);
    return p[x];
}
void merge(int a, int b)
{
    int fa = find(a), fb = find(b);
    if(fa != fb) p[fa] = fb;
}
void fenzhi()
{
    int cnt1 = 0, cnt2 = 0;
    for(int i = 1; i <= N; ++ i)
    {
        if(p[i] == i && f[i] == true) ++ cnt1;
        if(f[i] == true) ++ cnt2;
    }
    cout << cnt2 << " " << cnt1 << endl;
}
int main()
{
    int n;
    cin >> n;
    init();
    for(int i = 1; i <= n; ++ i)
    {
        int k;
        scanf("%d",&k);
        int tmp;
        scanf("%d",&tmp);
        f[tmp] = true;
        for(int j = 1; j < k; ++ j)
        {
            int tmp2;
            scanf("%d",&tmp2);
            f[tmp2] = true;
            merge(tmp,tmp2);
        }
    }
    int q;
    cin >> q;
    fenzhi();
    for(int i = 1; i <= q; ++ i)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        if(find(a) == find(b)) cout << "Y\n";
        else cout << "N\n";
    }
    return 0;
}

相關文章