给定每个人的家庭成员和其自己名下的房产,请你统计出每个家庭的人口数、人均房产面积及房产套数。
输入格式:
输入第一行给出一个正整数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
代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB
思路分析:
这道题是使用并查集,凡是求与集合相关的信息,大多数都是使用并查集。这道题使用并查集需要维护几个信息:
- f[] 数组存放每个点的父节点是哪一个点,
- people[] 存放每个人的房子数和地产面积
- set<int> st,使用它来保证我们遍历每个人时不会重复遍历,自动去重
- map<id, answer> mp;
- 结构体 answer, People.
代码如下:
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
const int N = 10050;
struct People{ //People中P是大写;
int house;
int s;
}people[N];
struct answer{
int minid;
int num;
int rooms;
double s;
bool operator<(const answer &A)const{
if(s * 1.0 / num == A.s * 1.0 / A.num){
return minid < A.minid;
}
else return s * 1.0 / num > A.s * 1.0 / A.num;
}
};
unordered_map<int, answer> mp;
unordered_set<int> st;
int f[N];
int find(int x)
{
if(x != f[x]) f[x] = find(f[x]);
return f[x];
}
void init()
{
for(int i = 1; i < N; i ++) f[i] = i;
}
void merge(int x, int y)//合并两个元素
{
int tx = find(x), ty = find(y);
if(tx != ty)
{
if(tx > ty) f[tx] = ty;
else f[ty] = tx;
}
}
void getpeople()
{
int id, mother, father, knum;
cin >> id >> father >> mother >> knum;
st.insert(id);
if(father != -1)
{
st.insert(father);
merge(father, id);
}
if(mother != -1)
{
st.insert(mother);
merge(mother, id);
}
while(knum --)
{
int k;
cin >> k;
st.insert(k);
merge(k, id);
}
cin >> people[id].house >> people[id].s;
}
void solve()
{
//更新set集合st;
for(auto i : st)
{
int id = find(i);
mp[id].minid = id;
mp[id].num ++;
mp[id].rooms += people[i].house;
mp[id].s += people[i].s;
}
//先在mp中存放的就是每个家庭的信息;
cout << mp.size() << endl;
vector<answer> res;
for(auto i : mp) res.push_back(i.second);
//对其进行排序,前面已经在结构体中重载小于号了
sort(res.begin(), res.end());
//最后输出结果
for(int i = 0; i < res.size(); i ++)
{
printf("%04d %d %.3lf %.3lf\n", res[i].minid, res[i].num, res[i].rooms * 1.0 / res[i].num, res[i].s / res[i].num);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
init();//初始化每个节点
int n;
cin >> n;
while(n --) getpeople();
solve();
return 0;
}