PAT (Advanced Level) Practice A1118 Birds in Forest (25 分)(C++)(甲级)(并查集、set)

本文介绍了一种使用并查集和集合进行数据结构操作的方法,实现对元素的快速查找和集合统计,时间复杂度为O(N)。通过路径压缩优化,确保每个集合只有一个根节点,便于统计集合数量及元素总数。

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

//用了并查集和集合来解决,时间复杂度O(N)
const int MAX = 10010, INF = 1<<30;
int N, K, Q;
int father[MAX];
set<int> S;//集合用来统计集合的个数和集合中元素的个数
int cnt = 0;

int findFather(int a)
{
    int aF = a;
    while(aF != father[aF]) aF = father[aF];
    while(a != aF)
    {
        int temp = father[a];
        father[a] = aF;
        a = temp;
    }
    return aF;
}

int main()
{
    for(int i=0; i<MAX; i++) father[i] = i;
    scanf("%d", &N);
    for(int i=0; i<N; i++)
    {
        scanf("%d", &K);
        int F, X;
        if(K) scanf("%d", &F);
        S.insert(F);
        for(int j=1; j<K; j++)
        {
            scanf("%d", &X);
            if(X == father[X]) father[X] = F;
            else
            {
                int xF = findFather(X);
                father[xF] = F;
            }
            S.insert(X);
        }
    }
    for(set<int>::iterator it = S.begin(); it != S.end(); it++)//先查询一遍,利用路径优化,让每个集合只有一个根节点
    {
        findFather(*it);
    }
    for(set<int>::iterator it = S.begin(); it != S.end(); it++)
    {
        if(father[*it] == *it) cnt++;//查询根节点个数,即集合个数(树的个数)
    }
    printf("%d %d\n", cnt, S.size());//集合大小即元素个数(鸟的个数)
    scanf("%d", &Q);
    for(int i=0; i<Q; i++)
    {
        int a, b;
        scanf("%d %d", &a, &b);
        if(father[a] != father[b]) printf("No\n");//不在同一个集合
        else printf("Yes\n");//在同一个集合
    }
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值