PAT A1114 Family Property 套路代码 并查集+排序

题目链接

我看别人代码觉得思路请求, 我就只会用固定的套路和格式。

#include <cstdio>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
struct Node{
	int id;
	double number,area;
	int people;
	double avgNum, avgArea;
	Node (){
		people=1;
	}
}node[10010];
bool cmp(int a, int b){
	if (node[a].avgArea!=node[b].avgArea) return node[a].avgArea>node[b].avgArea;
	else return node[a].id<node[b].id;
} 
int father[10010];
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;
	}
}
void init(){
	for (int i=0; i<10010; i++){
		father[i]=i;
		node[i].id=i;//不是所有人都有房子 
	}
}
int hashTable[10010]={0};
int n;
int main(){
	scanf("%d",&n);
	init();//重中之重 
	for (int i=0; i<n; i++){
		int id,fa,mo,childNum;
		scanf("%d %d %d %d",&id, &fa, &mo, &childNum); 
		hashTable[id]++;
		if (fa!=-1) {
			Union(id,fa);
			hashTable[fa]++;
		}
		if (mo!=-1) {
			Union(id,mo);
			hashTable[mo]++;
		}
		for (int j=0; j<childNum; j++){
			int temp;
			scanf("%d",&temp);
			Union(id, temp);
			hashTable[temp]++;
		}
		scanf("%lf %lf",&node[id].number, &node[id].area);
	}
	vector<int> family;
	int haveIn[10010]={0};
	for (int i=0; i<10010; i++){
		if (hashTable[i]){
			int father=findFather(i);
			if (!haveIn[father]){
				family.push_back(father);
				haveIn[father]=1;
			}
			if (father!=i){//这里很容易错 
				if (node[father].id>node[i].id){
					node[father].id=node[i].id;
				}
				node[father].area+=node[i].area;
				node[father].number+=node[i].number;
				node[father].people++;
			}
			node[father].avgArea=node[father].area/node[father].people;
			node[father].avgNum=node[father].number/node[father].people;
		}
	}
	sort(family.begin(), family.end(), cmp);
	printf("%d\n",family.size());
	for (int i=0; i<family.size(); i++){
		int index=family[i];
		printf("%04d %d %.3f %.3f\n",node[index].id, node[index].people, node[index].avgNum, node[index].avgArea);
	}
}

自己想太麻烦 还是用套路比较好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值