题154.2022寒假天梯赛训练&2021秋周练习-7-5 部落 (20 分)


题154.2022寒假天梯赛训练&2021秋周练习-7-5 部落 (20 分)


一、题目

在这里插入图片描述

二、题解

无话可说,直接无脑并查集。。。

#include <bits/stdc++.h>

using namespace std;

const int Maxsize=10010;
int parent[Maxsize];
int total=0,num=0;
int maxindex=0;

void init()
{
    fill(parent,parent+Maxsize,-1);
    return;
}

int findRoot(int v)
{
    if(parent[v]<0)
    {
        return v;
    }
    else
    {
        return parent[v]=findRoot(parent[v]);
    }
}

void unionSet(int v1,int v2)
{
    int root1=findRoot(v1);
    int root2=findRoot(v2);
    if(root1==root2)
    {
        return;
    }
    if(parent[root1]<parent[root2])
    {
        parent[root1]+=parent[root2];
        parent[root2]=root1;
    }
    else
    {
        parent[root2]+=parent[root1];
        parent[root1]=root2;
    }
    return;
}

void caculateSet()
{
    for(int i=1;i<=maxindex;i++)
    {
        if(parent[i]<0)
        {
            total-=parent[i];
            num++;
        }
    }
}

int checkSet(int v1,int v2)
{
    int root1=findRoot(v1);
    int root2=findRoot(v2);
    if(root1==root2)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    init();
    int N;
    cin>>N;
    for(int i=0;i<N;i++)
    {
        int K;
        scanf("%d",&K);
        int last;
        for(int j=0;j<K;j++)
        {
            int now;
            scanf("%d",&now);
            maxindex=max(maxindex,now);
            if(j>0)
            {
                unionSet(last,now);
            }
            last=now;
        }
    }
    caculateSet();
    cout<<total<<" "<<num<<endl;
    int Q;
    cin>>Q;
    for(int i=0;i<Q;i++)
    {
        int v1,v2;
        scanf("%d%d",&v1,&v2);
        if(checkSet(v1,v2))
        {
            printf("Y\n");
        }
        else
        {
            printf("N\n");
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值