PAT甲级1118

题目大意:
	一组鸟在一棵树上,多组输入(集合的合并),判断两只鸟是否在同一棵树上。
	并查集。
个人思路:
设置二维数组,一个集合的放入一组数组之中。
——每次要遍历,找到相同元素,然后存入?——时间复杂度n*k

算法改进:并查集:将每个集合中一个记为最上级,之后每加入元素,找这组元素的最上级即可,最终最上级(通过find()函数找到)个数即为集合个数。——空间优化,时间优化。
并查集(模板):——就是通过设置、查找集合的最上级来解决集合合并问题。

pre[ ]:记录每个元素的上级 //上级为自己的人即为一个最上级
find():查找最上级

此题目:
不是一次两个数据合并,而是一次多组数据。
统计有多少最上级(easy)——cnt[]数组:对数组的处理统计方式——找根,路径压缩,cnt++;
并且统计集合总数目
//初始代码——简单思路——看清题目要求!!!
//看清题目:问的是birds总数,
/*#include<bits/stdc++.h>
#define MAXN 10005
using namespace std;
int pre[MAXN];
int find_root(int root){
    int son, temp;
    son = root;
    while(root != pre[root]){
        root = pre[root];
    }
    while(son != pre[root]){ //路径压缩
        temp = pre[son];
        pre[son] = root;
        son = temp;
    }
    return root;
}

int count_root(int root,int maxn){
    int cnt = 0;
    for(int i = 1; i <= maxn; i++){
        if(pre[i] == root)
            cnt++;
    }
    return cnt;
}

int main(){
    int n, k, b1, b2, root1, root2;
    cin >> n;
    for(int i = 0; i <= 10005; i++)
        pre[i] = i;
    int maxn = -1;
    while(n--){
        cin >> k >> b1;
        maxn = maxn > b1?maxn:b1;
        root1 = find_root(b1);
        for(int i = 1; i < k; i++){
            cin >> b2;
            root2 = find_root(b2);
            maxn = maxn > b2?maxn:b2;
            if(root1!=root2){
                root1 = pre[root2];         /*join()函数的实现过程
                find_root(root2);//目的:路径压缩
            }
        }
    }
        int cnt  = 0, cnt_num, max_cnt = 0;
        for(int i = 1; i <= maxn; i++){
            if(pre[i] == i){
                cnt++;
                cnt_num = count_root(i, maxn);
                max_cnt = max_cnt > cnt_num?max_cnt:cnt_num;
            }
        }
        cout << cnt << " " << max_cnt << endl;
        int num, r1, r2, root3, root4;
        cin >> num;
        while(num--){
            cin >> r1 >> r2;
            root3 = find_root(r1);
            root4 = find_root(r2);
            if(root3==root4) cout << "Yes" << endl;
            else cout << "No" << endl;
        }
        return 0;

}
//改正思路代码 //改进point:cnt[]数组来统计i最高级的集合的数目,exist[] 为bool型,记录鸟出现过
//一定要!!!!清楚题目要求。
//错误点:没有路径压缩,把间接的上级转化到为最上级,因此cnt[]数组数根时多了出来 //已改正
#include<bits/stdc++.h>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值