L2-007 家庭房产 (25 分)

本文介绍了一种使用并查集数据结构解决家庭成员与房产统计问题的方法。通过输入每个人的详细信息,包括家庭成员和房产数据,算法能够统计出每个家庭的人口数、人均房产面积及人均房产套数,并按照特定格式输出。文章详细解释了并查集的初始化、查找和合并操作,以及如何利用这些操作来构建家庭关系图,并最终计算出所需统计数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定每个人的家庭成员和其自己名下的房产,请你统计出每个家庭的人口数、人均房产面积及房产套数。

输入格式:

输入第一行给出一个正整数N(≤1000),随后N行,每行按下列格式给出一个人的房产:

编号 父 母 k 孩子1 ... 孩子k 房产套数 总面积

其中编号是每个人独有的一个4位数的编号;分别是该编号对应的这个人的父母的编号(如果已经过世,则显示-1);k(0≤k≤5)是该人的子女的个数;孩子i是其子女的编号。

输出格式:

首先在第一行输出家庭个数(所有有亲属关系的人都属于同一个家庭)。随后按下列格式输出每个家庭的信息:

家庭成员的最小编号 家庭人口数 人均房产套数 人均房产面积

其中人均值要求保留小数点后3位。家庭信息首先按人均面积降序输出,若有并列,则按成员编号的升序输出。

输入样例:

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

输出样例:

3
8888 1 1.000 1000.000
0001 15 0.600 100.000
5551 4 0.750 100.000

思路:用并查集。

程序:

#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
using namespace std;
struct fam
{
	int id,num;
	double avg1,avg2;
};
const int N = 10000;
int father[N];
int root[N];
bool cmp(struct fam a,struct fam b)
{
	if(a.avg2 != b.avg2)
		return a.avg2 > b.avg2;
	else
		return a.id < b.id;
}
void Init()
{
	for(int i = 0; i < N; i++)
	{
		father[i] = i;
	}
}
int Find(int a)
{
	while(father[a] != a)
		a = father[a];
	return a;
}
void Union(int a,int b)
{
	int fa = Find(a);
	int fb = Find(b);
	if(fa > fb)
		father[fa] = fb;
	else if(fa < fb)
		father[fb] = fa;
}
int main()
{
	int n;
	scanf("%d",&n);
	Init();
	map<int,int> mp1;
	map<int,int> mp2;
	map<int,int> mp3;
	map<int,int> mp4;
	map<int,int> mp5;
	set<int> st;
	for(int i = 0; i < n; i++)
	{
		int id,dad,mom,k;
		scanf("%d%d%d%d",&id,&dad,&mom,&k);
		st.insert(id);
		if(dad != -1)
		{
			st.insert(dad);
		    Union(id,dad);
		}
		if(mom != -1)
		{
			st.insert(mom);
			Union(id,mom);
		}
		for(int j = 0; j < k; j++)
		{
			int child;
			scanf("%d",&child);
			Union(id,child);
			st.insert(child);
		}
		int house,area;
		scanf("%d%d",&house,&area);
		mp1[id] = house;
		mp2[id] = area;
	}
	set<int>::iterator it;
	int count = 0;
	for(it = st.begin(); it != st.end(); it++)
	{
		int temp = Find(*it);
		if(root[temp] == 0)
			count++;
		root[temp]++;
		if(mp1[*it])
		{
			mp3[temp] += mp1[*it];
			mp4[temp] += mp2[*it];
		}
	}
	vector<fam> v(count);
	int t = 0;
	for(int i = 0; i < N; i++)
	{
		if(root[i])
		{
			v[t].id = i;
			v[t].num = root[i];
			v[t].avg1 = mp3[i] * 1.0 / root[i];
			v[t].avg2 = mp4[i] * 1.0 / root[i];
			t++;
		}
	}
	sort(v.begin(),v.end(),cmp);
	printf("%d\n",count);
	for(int i = 0; i < count; i++)
	{
		printf("%04d %d %.3lf %.3lf\n",v[i].id,v[i].num,v[i].avg1,v[i].avg2);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值