给定一个人的id、父亲id、母亲id、孩子个数、孩子id、房产套数、房产面积,求每个家庭的最小id、人口数、人均房产套数、人均房产面积。按人均面积降序输出,如果有相同按id升序输出。
用dfs做,将父子/母子关系存成图,深搜找出所有有联系的节点。然后将相应的值加在家庭的节点上。当一次深搜完成后还有没被访问到的节点时,将从id值最小的节点开始进行新一轮的深搜。最后排序输出。
#include <bits/stdc++.h>
#define INF 9999999
using namespace std;
const int maxn=10010;
int m,n,cnt=0,familyid=0;
int father[maxn];
struct Node{
int id=10000,sets=0,area=0,cnt=0;
friend bool operator <(Node a,Node b){
float aa=a.area*1.0/a.cnt,bb=b.area*1.0/b.cnt;
if(aa!=bb)return aa>bb;
else return a.id<b.id;
}
}node[maxn];
set<int> member;
vector<int> g[maxn];
vector<Node> family(maxn);
map<int,int> mp;
int vis[maxn];
int getIdx(int id){
auto it=mp.find(id);
int res;
if(it==mp.end()){
res=mp.size();
mp[id]=res;
}else res=it->second;
return res;
}
void dfs(int curr,int familyid){
if(vis[curr]) return;
family[familyid].area+=node[curr].area;
family[familyid].sets+=node[curr].sets;
family[familyid].cnt++;
int a=family[familyid].area;
if(family[familyid].id>curr)family[familyid].id=curr;
cnt++;
vis[curr]=true;
for(int i=0;i<g[curr].size();i++)dfs(g[curr][i],familyid);
}
int main(){
cin>>n;
fill(vis,vis+maxn,-1);
for(int i=0;i<n;i++){
int selfid,fatid,motid,childnum,estnum,area;
cin>>selfid>>fatid>>motid>>childnum;
if(fatid!=-1){
g[fatid].push_back(selfid);
g[selfid].push_back(fatid);
vis[fatid]=0;
member.insert(fatid);
}
if(motid!=-1){
int motidx=getIdx(motid);
g[motid].push_back(selfid);
g[selfid].push_back(motid);
vis[motid]=0;
member.insert(motid);
}
node[selfid].id=selfid;
for(int j=0;j<childnum;j++){
int childid,childidx;
cin>>childid;
g[selfid].push_back(childid);
g[childid].push_back(selfid);
vis[childid]=0;
member.insert(childid);
}
vis[selfid]=0;
member.insert(selfid);
cin>>node[selfid].sets>>node[selfid].area;
}
while(cnt!=member.size()){
int idx=0;
while(vis[idx]!=0)idx++;
dfs(idx,familyid);
familyid++;
}
printf("%d\n",familyid);
sort(family.begin(),family.begin()+familyid);
for(int i=0;i<familyid;i++){
printf("%04d %d %.3f %.3f\n",family[i].id,family[i].cnt,family[i].sets*1.0/family[i].cnt,family[i].area*1.0/family[i].cnt);
}
}