【algo&ds】【pat】5.并查集及其应用

1.并查集的定义

在计算机科学中,并查集是一种树型的数据结构,用于处理一些不交集(Disjoint Sets)的合并及查询问题。有一个联合-查找算法(union-find algorithm)定义了两个用于此数据结构的操作:

  • Find:确定元素属于哪一个子集。

  • Union:将两个子集合并成同一个集合。

  • MakeSet,用于建立单元素集合。

为了更加精确的定义这些方法,需要定义如何表示集合。一种常用的策略是为每个集合选定一个固定的元素,称为代表,以表示整个集合。接着,Find(x) 返回x所属集合的代表,而Union使用两个集合的代表作为参数。

并查集森林是一种将每一个集合以树表示的数据结构,其中每一个节点保存着到它的父节点的引用

Snipaste_2019-11-19_16-45-58.png

比如上面是两个集合分别记为A和B,集合A有4个元素,集合B有3个元素,每个元素都只对应一个集合,也就是一对一,对于集合的表示,通常都是使用根节点来判断,也就是说,1和5分别表示两个集合

//集合1的元素
1,2,3,4
//集合5的元素
5,6,7

那么

find(1)=1
find(2)=1
find(3)=1
find(4)=1

find(5)=5
find(6)=5
find(7)=5

2.并查集的基本操作

2.1并查集的存储结构

并查集通常用一个数组来表示,

int father[N];

其中father[i]表示元素i的父亲节点,而父亲节点本身也是这个集合内的元素,判断一个元素的集合代表,就是一直遍历元素的父亲节点,一直到father[i]=i,表示元素i的父亲节点是它自己,则遍历结束,用这个元素i来表示这个集合。

2.2并查集的初始化

一开始,每一个元素都是一个独立的集合,那么这个元素本身就可以代表集合,所以需要令father[i]等于i(1<=i<=N)。

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

2.3查找

查找一个元素所在的集合就是查找树的根节点,可以通过递归或者迭代来实现。

递归查找

int find(int x){
    if(x == father[x]) return x;
    else return find(father[x]);
}

迭代查找

int find(int x){
    while(x != father[x]){
        x = father[x];
    }
    return x;
}

2.4合并

合并操作是对两个不同的集合合并成一个集合,接收两个元素,判断两个元素是否在不同的集合上,然后将其中一个集合的根节点的父亲结点指向另一个集合的根节点即可。

void union(int a, int b){
    int faA = find(a);
    int fab = find(b);
    if(faa != fab){
        father[faa] = fab;
    }
}

3.并查集的优化

存在一种极端情况,树的逻辑结构是斜二叉树,也就是树退化成了单链表,每次查找的时候时间复杂度都是O(n)。一种优化思路是,把每一个元素的父亲节点直接指向根节点。

int find(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;
}

4.并查集的应用

以下是PAT的三道关于并查集的问题。

1107 Social Clusters

When register on a social network, you are always asked to specify your hobbies in order to find some
potential friends with the same hobbies. A “social cluster” is a set of people who have some of their
hobbies in common. You are supposed to find all the clusters.Input Specification:
Each input file contains one test case. For each test case, the first line contains a positive integer N
(<=1000), the total number of people in a social network. Hence the people are numbered from 1 to N.
Then N lines follow, each gives the hobby list of a person in the format:
Ki: hi[1] hi[2] … hi[Ki]
where Ki (>0) is the number of hobbies, and hi[j] is the index of the j-th hobby, which is an integer in [1,
1000].Output Specification:
For each case, print in one line the total number of clusters in the network. Then in the second line, print
the numbers of people in the clusters in non-increasing order. The numbers must be separated by exactly
one space, and there must be no extra space at the end of the line.Sample Input:
8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4
Sample Output:
3
4 3 1

题目大意:有n个人,每个人喜欢k个活动,如果两个人有任意一个活动相同,就称为他们处于同一个社交网络。求这n个人一共形成了多少个社交网络。

需要注意的是如果A和B组成了一个集合,B和C组成了一个集合,那么A和B、C应该是在一个集合中的,尽管A和C并没有相同的活动

这道题是一道很经典的并查集问题,每个人喜欢的活动数目都不一样,根据活动来判断两个人是否属于同一个集合,每个人的编号就是集合的元素,编号从1开始到n,如果是同一个集合,则合并,最后遍历father数组的每一个元素,然后查找每一个元素的根节点,根据根节点来记录每一个集合的人数,最后统计这些集合个数即可。

#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;
			Union(i, findFather(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;
}

1114 Family Property

This time, you are supposed to help us collect the data for family-owned property. Given each person's family members, and the estate(房产)info under his/her own name, we need to know the size of each family, and the average area and number of sets of their real estate.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤1000). Then N lines follow, each gives the infomation of a person who owns estate in the format:

ID` `Father` `Mother` k Child1⋯Childk Mestate Area

where ID is a unique 4-digit identification number for each person; Father and Mother are the ID's of this person's parents (if a parent has passed away, -1 will be given instead); k (0≤k≤5) is the number of children of this person; Child**i's are the ID's of his/her children; Mestate is the total number of sets of the real estate under his/her name; and Area is the total area of his/her estate.

Output Specification:

For each case, first print in a line the number of families (all the people that are related directly or indirectly are considered in the same family). Then output the family info in the format:

ID M AVGsets AVGarea

where ID is the smallest ID in the family; M is the total number of family members; AVGsets is the average number of sets of their real estate; and AVGarea is the average area. The average numbers must be accurate up to 3 decimal places. The families must be given in descending order of their average areas, and in ascending order of the ID's if there is a tie.

Sample Input:

10
6666 5551 5552 1 7777 1 100
1234 5678 9012 1 0002 2 300
8888 -1 -1 0 1 1000
2468 0001 0004 1 2222 1 500
7777 6666 -1 0 2 300
3721 -1 -1 1 2333 2 150
9012 -1 -1 3 1236 1235 1234 1 100
1235 5678 9012 0 1 50
2222 1236 2468 2 6661 6662 1 300
2333 -1 3721 3 6661 6662 6663 1 100

Sample Output:

3
8888 1 1.000 1000.000
0001 15 0.600 100.000
5551 4 0.750 100.000
#include <cstdio>
#include <algorithm>
using namespace std;
struct DATA {
	int id, fid, mid, num, area;
	int cid[10];
} data[1005];
struct node {
	int id, people;
	double num, area;
	bool flag = false;
} ans[10000];
int father[10000];
bool visit[10000];
int find(int x) {
	while(x != father[x])
		x = father[x];
	return x;
}
void Union(int a, int b) {
	int faA = find(a);
	int faB = find(b);
	if(faA > faB)
		father[faA] = faB;
	else if(faA < faB)
		father[faB] = faA;
}
int cmp1(node a, node b) {
	if(a.area != b.area)
		return a.area > b.area;
	else
		return a.id < b.id;
}
int main() {
	int n, k, cnt = 0;
	scanf("%d", &n);
	for(int i = 0; i < 10000; i++)
		father[i] = i;
	for(int i = 0; i < n; i++) {
		scanf("%d %d %d %d", &data[i].id, &data[i].fid, &data[i].mid, &k);
		visit[data[i].id] = true;
		if(data[i].fid != -1) {
			visit[data[i].fid] = true;
			Union(data[i].fid, data[i].id);
		}
		if(data[i].mid != -1) {
			visit[data[i].mid] = true;
			Union(data[i].mid, data[i].id);
		}
		for(int j = 0; j < k; j++) {
			scanf("%d", &data[i].cid[j]);
			visit[data[i].cid[j]] = true;
			Union(data[i].cid[j], data[i].id);
		}
		scanf("%d %d", &data[i].num, &data[i].area);
	}
	for(int i = 0; i < n; i++) {
		int id = find(data[i].id);
		ans[id].id = id;
		ans[id].num += data[i].num;
		ans[id].area += data[i].area;
		ans[id].flag = true;
	}
	for(int i = 0; i < 10000; i++) {
		if(visit[i])
			ans[find(i)].people++;
		if(ans[i].flag)
			cnt++;
	}
	for(int i = 0; i < 10000; i++) {
		if(ans[i].flag) {
			ans[i].num = (double)(ans[i].num * 1.0 / ans[i].people);
			ans[i].area = (double)(ans[i].area * 1.0 / ans[i].people);
		}
	}
	sort(ans, ans + 10000, cmp1);
	printf("%d\n", cnt);
	for(int i = 0; i < cnt; i++)
		printf("%04d %d %.3f %.3f\n", ans[i].id, ans[i].people, ans[i].num,
		       ans[i].area);
	return 0;
}

1118 Birds in Forest

Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive number N (≤10
^4 ) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B1 B2 ... BK

where K is the number of birds in this picture, and Bi 's are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than 10^4

After the pictures there is a positive number Q (≤10^4 ) which is the number of queries. Then Q lines follow, each contains the indices of two birds.

Output Specification:
For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line Yes if the two birds belong to the same tree, or No if not.

Sample Input:
4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7Sample Output:
2 10
Yes
No

#include <iostream>
using namespace std;
int n, m, k;
const int maxn = 10010;
int fa[maxn] = {0}, cnt[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;
}
bool exist[maxn];
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值