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