【PAT甲级复习】 专题复习二:并查集

并查集主要用来处理一些分组和分类的问题,实现起来也比较简单,主要包含以下几个操作:

1 初始化

int father[N];
for(int i=1; i<=N i++){
    father[i] = i;
}

2 查找根节点+路径压缩

int findFather(int x){
    int t = x;
    while(x != father[x]) x = father[x];
    while(t != father[t]){
        int z = t;
        t = father[t];
        father[z] = x;
    }
    return x;
}

3 集合合并

int Union(int a, int b){
    int faA = findFather(a);
    int faB = findFather(b);
    if(faA != faB) father[faA] = faB;
}

4 常见的一些统计数据

// 统计有多少个团体(numTrees),每个团体多少人(cnt[i]),总共有多少人(numBirds)
for(int i = 1; i <= maxn; i++) {
	if(exist[i] == true) {
		int root = findFather(i);
		cnt[root]++;
	}
}

int numTrees = 0, numBirds = 0;
for(int i = 1; i <= maxn; i++) {
	if(exist[i] == true && cnt[i] != 0) {
    	numTrees++;
		numBirds += cnt[i];
	}
}

5 STL中与集合操作相关的函数

(1条消息) STL容器的并集(set_union)、交集(set_intersection)和差集(set_difference)函数的使用_DayDayUp-CSDN博客

注意需要进行集合操作的两个容器必须是有序的(递增排序)!

  • set_intersection()
  • set_union()
  • set_difference()
#include<bits/stdc++.h> 
using namespace std;
int main(){
	set<string> words1 {"one", "two", "three", "four", "five", "six"};
	set<string> words2 {"four","five", "six", "seven", "eight", "nine"};
	set<string> result;
	set_intersection(words1.begin(), words1.end(), words2.begin(), words2.end(), inserter(result, result.begin()));
	for(auto it = result.begin(); it != result.end(); it++){
		cout << *it << endl;
	}
	// Result: "five" "four" "six"	
}


// set_union example
#include <iostream>     // std::cout
#include <algorithm>    // std::set_union, std::sort
#include <vector>       // std::vector

int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  std::vector<int> v(10);                      // 0  0  0  0  0  0  0  0  0  0
  std::vector<int>::iterator it;

  std::sort (first,first+5);     //  5 10 15 20 25
  std::sort (second,second+5);   // 10 20 30 40 50

  it=std::set_union (first, first+5, second, second+5, v.begin());
                                               // 5 10 15 20 25 30 40 50  0  0
  v.resize(it-v.begin());                      // 5 10 15 20 25 30 40 50
  std::cout << "The union has " << (v.size()) << " elements:\n";
  for (it=v.begin(); it!=v.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
  return 0;
}

6 例题解析

6.1 A1107 Social Clusters (30 分)

考察并查集的典型例题,**读懂题意很关键!**如果当前读取到的某个人的某个爱好之前并没有被其他人喜欢过,就设置当前这个人作为这个爱好的leader,如果已经有其他人喜欢过,就合并当前这个人和该爱好的leader。

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> father, isRoot;
int cmp1(int a, int b){
    return a > b;
}
int findFather(int x) {
    int a = x;
    while(x != father[x])
        x = father[x];
    while(a != father[a]) {
        int z = a;
        a = father[a];
        father[z] = x;
    }
    return x;
}
void Union(int a, int b) {
    int faA = findFather(a);
    int faB = findFather(b);
    if(faA != faB)
        father[faA] = faB;
}
int main() {
    int n, k, t, cnt = 0;
    int course[1001] = {0};
    scanf("%d", &n);
    father.resize(n + 1);
    isRoot.resize(n + 1);
    for(int i = 1; i <= n; i++)
        father[i] = i;
    for(int i = 1; i <= n; i++) {
        scanf("%d:", &k);
        for(int j = 0; j < k; j++) {
            scanf("%d", &t);
            if(course[t] == 0)
                course[t] = i;
            else
                Union(i, course[t]);
        }
    }
    for(int i = 1; i <= n; i++)
        isRoot[findFather(i)]++;
    for(int i = 1; i <= n; i++) {
        if(isRoot[i] != 0)
            cnt++;
    }
    printf("%d\n", cnt);
    sort(isRoot.begin(), isRoot.end(), cmp1);
    for(int i = 0; i < cnt; i++) {
        printf("%d", isRoot[i]);
        if(i != cnt - 1) printf(" ");
    }
    return 0;
}
6.2 A1118 Birds in Forest (25 分)

经典模板题。

#include <iostream>
using namespace std;
int n, m, k;
const int maxn = 10005;
int fa[maxn] = {0}, cnt[maxn] = {0};
bool exist[maxn] = {0};
int findFather(int x) {
    int a = x;
    while(x != fa[x])
        x = fa[x];
    while(a != fa[a]) {
        int z = a;
        a = fa[a];
        fa[z] = x;
    }
    return x;
}
void Union(int a, int b) {
    int faA = findFather(a);
    int faB = findFather(b);
    if(faA != faB) fa[faA] = faB;
}
int main() {
    scanf("%d", &n);
    for(int i = 1; i <= maxn; i++)
        fa[i] = i;
    int id, temp;
    for(int i = 0; i < n; i++) {
        scanf("%d%d", &k, &id);
        exist[id] = true;
        for(int j = 0; j < k-1; j++) {
            scanf("%d", &temp);
            Union(id, temp);
            exist[temp] = true;
        }
    }
    for(int i = 1; i <= maxn; i++) {
        if(exist[i] == true) {
            int root = findFather(i);
            cnt[root]++;
        }
    }
    int numTrees = 0, numBirds = 0;
    for(int i = 1; i <= maxn; i++) {
        if(exist[i] == true && cnt[i] != 0) {
            numTrees++;
            numBirds += cnt[i];
        }
    }
    printf("%d %d\n", numTrees, numBirds);
    scanf("%d", &m);
    int ida, idb;
    for(int i = 0; i < m; i++) {
        scanf("%d%d", &ida, &idb);
        printf("%s\n", (findFather(ida) == findFather(idb)) ? "Yes" : "No");
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值