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

输入格式:
输入第一行给出一个正整数 L2-007 家庭房产 (25 分) - C++_c++,随后 L2-007 家庭房产 (25 分) - C++_排序_02 行,每行按下列格式给出一个人的房产:

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

其中编号是每个人独有的一个 ​​4​​​ 位数的​​编号​​​;​​父​​​和​​母​​​分别是该编号对应的这个人的父母的编号(如果已经过世,则显示 ​​-1​​​);L2-007 家庭房产 (25 分) - C++_c++_03是该人的子女的个数;孩子 ​​​i​​ 是其子女的编号。

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

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

其中人均值要求保留小数点后 L2-007 家庭房产 (25 分) - C++_并查集_04 位。家庭信息首先按人均面积降序输出,若有并列,则按成员编号的升序输出。

输入样例:

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 <iostream>
#include <unordered_set>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 10100;

int n;
// pre数组, 房子数, 面积, 人数
int p[N], houseCnt[N], area[N], cnt[N];
unordered_set<int> ps; // 记录所有的人

// 家庭
struct Fm{
int id, cnt;
double avgArea, avgHouseCnt;
bool operator < (const Fm & o) const {
if(this->avgArea == o.avgArea){
return id < o.id;
}
return avgArea > o.avgArea;
}
};

vector<Fm> res;

void init(){
for(int i = 0; i < N; i++) p[i] = i;
}

// 查找
int find(int x){
if(x != p[x]) p[x] = find(p[x]);
return p[x];
}
// 合并
void merge(int a, int b){
a = find(a), b = find(b);
if(a < b) swap(a, b);
p[a] = b;
}

int main(){

cin >> n;
int m = n;

init();

while(m--){

int id, fa, ma, k;
cin >> id >> fa >> ma >> k;
ps.insert(id);

if(fa != -1){
ps.insert(fa);
merge(id, fa);
}
if(ma != -1){
ps.insert(ma);
merge(id, ma);
}
int child;
while(k--){
cin >> child;
ps.insert(child);
merge(child, id);
}
int ct, ar;
cin >> ct >> ar;
houseCnt[id] += ct;
area[id] += ar;
}

// 计算 房子数, 面积, 人数
for(int id: ps){
int pre = find(id);
cnt[pre]++;
if(id != pre){
houseCnt[pre] += houseCnt[id];
area[pre] += area[id];
}
}
// 将每个家庭加入列表中
for(int id: ps){
if(id == p[id]){
res.push_back({id, cnt[id], area[id] * 1.0 / cnt[id], houseCnt[id] * 1.0 / cnt[id]});
}
}

sort(res.begin(), res.end()); // 排序

cout << res.size() << endl;

for(auto pson: res){
printf("%04d %d %.3lf %.3lf\n", pson.id, pson.cnt, pson.avgHouseCnt, pson.avgArea);
}

return 0;
}