PAT (Advanced Level)1118. Birds in Forest (25)&&1114. Family Property (25)并查集找爸爸

1114与1118为同一知识点,遂放在一起

并查集知识点,没接触过。看到这道题真的思考了好久没有思路。网上查了大佬的解析和代码豁然开朗。

当初在另外一本书上看见过并查集知识点,讲的云里雾里,太过于功力就放弃了。

在网上看见了这版讲解,通俗易懂非常好。

所以我认为并查集其实就是一个找爸爸的过程QAQ。

以下为转载至上述连接的并查集内容


话说江湖上散落着各式各样的大侠,有上千个之多。他们没有什么正当职业,整天背着剑在外面走来走去,碰到和自己不是一路人的,就免不了要打一架。但大侠们有一个优点就是讲义气,绝对不打自己的朋友。而且他们信奉“朋友的朋友就是我的朋友”,只要是能通过朋友关系串联起来的,不管拐了多少个弯,都认为是自己人。这样一来,江湖上就形成了一个一个的帮派,通过两两之间的朋友关系串联起来。而不在同一个帮派的人,无论如何都无法通过朋友关系连起来,于是就可以放心往死了打。但是两个原本互不相识的人,如何判断是否属于一个朋友圈呢?

我们可以在每个朋友圈内推举出一个比较有名望的人,作为该圈子的代表人物。这样,每个圈子就可以这样命名“中国同胞队”美国同胞队”……两人只要互相对一下自己的队长是不是同一个人,就可以确定敌友关系了。

但是还有问题啊,大侠们只知道自己直接的朋友是谁,很多人压根就不认识队长 抓狂 要判断自己的队长是谁,只能漫无目的的通过朋友的朋友关系问下去:“你是不是队长?你是不是队长?”这样,想打一架得先问个几十年,饿都饿死了,受不了。这样一来,队长面子上也挂不住了,不仅效率太低,还有可能陷入无限循环中。于是队长下令,重新组队。队内所有人实行分等级制度,形成树状结构,我队长就是根节点,下面分别是二级队员、三级队员。每个人只要记住自己的上级是谁就行了。遇到判断敌友的时候,只要一层层向上问,直到最高层,就可以在短时间内确定队长是谁了。由于我们关心的只是两个人之间是否是一个帮派的,至于他们是如何通过朋友关系相关联的,以及每个圈子内部的结构是怎样的,甚至队长是谁,都不重要了。所以我们可以放任队长随意重新组队,只要不搞错敌友关系就好了。于是,门派产生了。



















下面我们来看并查集的实现。 int pre[1000]; 这个数组,记录了每个大侠的上级是谁。大侠们从1或者0开始编号(依据题意而定),pre[15]=3就表示15号大侠的上级是3号大侠。如果一个人的上级就是他自己,那说明他就是掌门人了,查找到此为止。也有孤家寡人自成一派的,比如欧阳锋,那么他的上级就是他自己。每个人都只认自己的上级。比如胡青牛同学只知道自己的上级是杨左使。张无忌是谁?不认识!要想知道自己的掌门是谁,只能一级级查上去。 

find这个函数就是找掌门用的,意义再清楚不过了(路径压缩算法先不论,后面再说)。


[cpp]  view plain  copy
  1. int unionsearch(int root) //查找根结点  
  2. {  
  3.     int son, tmp;  
  4.     son = root;  
  5.     while(root != pre[root]) //我的上级不是掌门  
  6.         root = pre[root];  
  7.     while(son != root) //我就找他的上级,直到掌门出现  
  8.     {  
  9.         tmp = pre[son];  
  10.         pre[son] = root;  
  11.         son = tmp;  
  12.     }  
  13.     return root; //掌门驾到~~  
  14. }  


 再来看看join函数,就是在两个点之间连一条线,这样一来,原先它们所在的两个板块的所有点就都可以互通了。这在图上很好办,画条线就行了。但我们现在是用并查集来描述武林中的状况的,一共只有一个pre[]数组,该如何实现呢? 还是举江湖的例子,假设现在武林中的形势如图所示。虚竹帅锅与周芷若MM是我非常喜欢的两个人物,他们的终极boss分别是玄慈方丈和灭绝师太,那明显就是两个阵营了。我不希望他们互相打架,就对他俩说:“你们两位拉拉勾,做好朋友吧。”他们看在我的面子上,同意了。这一同意可非同小可,整个少林和峨眉派的人就不能打架了。这么重大的变化,可如何实现呀,要改动多少地方?其实非常简单,我对玄慈方丈说:“大师,麻烦你把你的上级改为灭绝师太吧。这样一来,两派原先的所有人员的终极boss都是师太,那还打个球啊!大笑反正我们关心的只是连通性,门派内部的结构不要紧的。”玄慈一听肯定火大了:“我靠,凭什么是我变成她手下呀,怎么不反过来?我抗议!”于是,两人相约一战,杀的是天昏地暗,风云为之变色啊,但是啊,这场战争终究会有胜负,胜者为王。弱者就被吞并了。反正谁加入谁效果是一样的,门派就由两个变成一个了。这段函数的意思明白了吧?


[cpp]  view plain  copy
  1. void join(int root1, int root2) //虚竹和周芷若做朋友  
  2. {  
  3.     int x, y;  
  4.     x = unionsearch(root1);//我老大是玄慈  
  5.     y = unionsearch(root2);//我老大是灭绝  
  6.     if(x != y)   
  7.         pre[x] = y; //打一仗,谁赢就当对方老大  
  8. }  

再来看看路径压缩算法。建立门派的过程是用join函数两个人两个人地连接起来的,谁当谁的手下完全随机。最后的树状结构会变成什么样,我也无法预知,一字长蛇阵也有可能。这样查找的效率就会比较低下。最理想的情况就是所有人的直接上级都是掌门,一共就两级结构,只要找一次就找到掌门了。哪怕不能完全做到,也最好尽量接近。这样就产生了路径压缩算法。

 设想这样一个场景:两个互不相识的大侠碰面了,想知道能不能干一场。 于是赶紧打电话问自己的上级:“你是不是掌门?” 上级说:“我不是呀,我的上级是谁谁谁,你问问他看看。” 一路问下去,原来两人的最终boss都是东厂曹公公。 “哎呀呀,原来是自己人,有礼有礼,在下三营六组白面葫芦娃!” “幸会幸会,在下九营十八组仙子狗尾巴花!” 两人高高兴兴地手拉手喝酒去了。 “等等等等,两位大侠请留步,还有事情没完成呢!”我叫住他俩。 “哦,对了,还要做路径压缩。”两人醒悟。 白面葫芦娃打电话给他的上级六组长:“组长啊,我查过了,其实偶们的掌门是曹公公。不如偶们一起结拜在曹公公手下吧,省得级别太低,以后查找掌门麻烦。” “唔,有道理。” 白面葫芦娃接着打电话给刚才拜访过的三营长……仙子狗尾巴花也做了同样的事情。 这样,查询中所有涉及到的人物都聚集在曹公公的直接领导下。每次查询都做了优化处理,所以整个门派树的层数都会维持在比较低的水平上。路径压缩的代码,看得懂很好,看不懂可以自己模拟一下,很简单的一个递归而已。总之它所实现的功能就是这么个意思。
















于是,问题圆满解决。。。。。。。。。

代码如下:

[cpp]  view plain  copy
  1. #include<iostream>  
  2. #include<cstdio>  
  3. #include<cstring>  
  4. #include<cmath>  
  5. #include<algorithm>  
  6. using namespace std;  
  7. int pre[1010]; //里面全是掌门  
  8.   
  9. int unionsearch(int root)  
  10. {  
  11.     int son, tmp;  
  12.     son = root;  
  13.     while(root != pre[root]) //寻找掌门ing……  
  14.         root = pre[root];  
  15.     while(son != root) //路径压缩  
  16.     {  
  17.         tmp = pre[son];  
  18.         pre[son] = root;  
  19.         son = tmp;  
  20.     }  
  21.     return root; //掌门驾到~  
  22. }  
  23.   
  24. int main()  
  25. {  
  26.     int num, road, total, i, start, end, root1, root2;  
  27.     while(scanf("%d%d", &num, &road) && num)  
  28.     {  
  29.         total = num - 1; //共num-1个门派  
  30.         for(i = 1; i <= num; ++i) //每条路都是掌门  
  31.             pre[i] = i;  
  32.         while(road--)  
  33.         {  
  34.             scanf("%d%d", &start, &end); //他俩要结拜  
  35.             root1 = unionsearch(start);  
  36.             root2 = unionsearch(end);  
  37.             if(root1 != root2) //掌门不同?踢馆!~  
  38.             {  
  39.                 pre[root1] = root2;  
  40.                 total--; //门派少一个,敌人(要建的路)就少一个  
  41.             }  
  42.         }  
  43.         printf("%d\n", total);//天下局势:还剩几个门派  
  44.     }  
  45.     return 0;  
  46. }  



1118. Birds in Forest (25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 (<= 104) 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 104.

After the pictures there is a positive number Q (<= 104) 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 7
Sample Output:
2 10
Yes
No


代码参考源

//1118. Birds in Forest(25)

#include <cstdio>
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];
		fa[a] = 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]++;//找到爸爸,爸爸孩子+1
		}

	}
	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);
		if (findFather(ida) == findFather(idb)) {//如果他俩同一个爸爸
			printf("Yes\n");
		}
		else {
			printf("No\n");
		}
	}
	return 0;
}

1114. Family Property (25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 M_estate 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; Childi's are the ID's of his/her children;M_estate 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 AVG_sets AVG_area

where ID is the smallest ID in the family; M is the total number of family members; AVG_sets is the average number of sets of their real estate; and AVG_area 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
1114比之1118要麻烦一些

代码参考源

#include <cstdio>  
#include <algorithm>  
using namespace std;
struct dat {
	int id, fid, mid, num, area;
	int cid[10];
}dat[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", &dat[i].id, &dat[i].fid, &dat[i].mid, &k);
		visit[dat[i].id] = true;
		if (dat[i].fid != -1) {
			visit[dat[i].fid] = true;
			Union(dat[i].fid, dat[i].id);
		}
		if (dat[i].mid != -1) {
			visit[dat[i].mid] = true;
			Union(dat[i].mid, dat[i].id);
		}
		for (int j = 0; j < k; j++) {
			scanf("%d", &dat[i].cid[j]);
			visit[dat[i].cid[j]] = true;
			Union(dat[i].cid[j], dat[i].id);
		}
		scanf("%d %d", &dat[i].num, &dat[i].area);
	}
	for (int i = 0; i < n; i++) {
		int id = find(dat[i].id);
		ans[id].id = id;
		ans[id].num += dat[i].num;
		ans[id].area += dat[i].area;
		ans[id].flag = true;
	}
	for (int i = 0; i < 10000; i++) {
		if (visit[i])
			ans[find(i)].people++;//找到该节点的顶级节点,其族系人数+1
		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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值