L2-007. 家庭房产
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定每个人的家庭成员和其自己名下的房产,请你统计出每个家庭的人口数、人均房产面积及房产套数。
输入格式:
输入第一行给出一个正整数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.0005551 4 0.750 100.000
思路:用并查集把亲戚关系的人并起来,最后再把权值不断给祖先。
代码加注释如下:
//https://www.patest.cn/contests/gplt/L2-007 //L2-007. 家庭房产 #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> const int inf=1999999999; const int maxn=10005; using namespace std; int f[maxn],tcount[maxn],area[maxn]; struct node { int tmin,people; double cnt,averagearea; }res[maxn]; int getf(int x)//找到祖先 { if(f[x]==x)return x; else { f[x]=getf(f[x]); return f[x]; } } int getfather(int x)//把钱给祖先 { if(f[x]==x)return x; int father=getf(x); tcount[father]+=tcount[x]; tcount[x]=0; area[father]+=area[x]; area[x]=0; return father; } bool cmp(node x,node y) { if(x.averagearea==y.averagearea)return x.tmin<y.tmin; return x.averagearea>y.averagearea; } void merge(int x,int y) { if(x==-1||y==-1||x==y)return; int fx=getf(x); int fy=getf(y); if(fx!=fy) { f[fy]=fx; } } int main() { int myself,father,mother,kidnum,n; while(scanf("%d",&n)==1) { bool vis[maxn]={false}; memset(tcount,0,sizeof(tcount)); memset(area,0,sizeof(area)); for(int i=0;i<maxn;i++)f[i]=i; for(int i=0;i<n;i++) { int housenum,housearea; scanf("%d%d%d%d",&myself,&father,&mother,&kidnum); int temp=-1,save[10],pos=3,kid; if(myself!=-1)temp=myself; if(father!=-1)temp=father; if(mother!=-1)temp=mother; save[0]=myself; save[1]=father; save[2]=mother; while(kidnum--) { scanf("%d",&kid); save[pos++]=kid; if(kid!=-1)temp=kid; } scanf("%d%d",&housenum,&housearea); if(temp!=-1)//把财产先随便给家庭中的任意一个活着的人 { tcount[temp]+=housenum; area[temp]+=housearea; } //cout<<"temp="<<temp<<endl; for(int j=0;j<pos;j++) { if(save[j]!=-1)vis[save[j]]=true;//存在该人 merge(temp,save[j]); } } int ans=0; //权值归并 for(int i=0;i<maxn;i++) { if(vis[i])f[i]=getfather(i); } //统计和输出 int cnt=0; for(int i=0;i<maxn;i++) { if(vis[i]&&f[i]==i) { ans++; int tmin=inf; int people=0; for(int j=0;j<maxn;j++) { if(f[j]==i) { tmin=min(tmin,j); people++; } } res[cnt].tmin=tmin; res[cnt].people=people; res[cnt].cnt=tcount[i]*1.0/(people*1.0); res[cnt].averagearea=area[i]*1.0/(people*1.0); cnt++; } } sort(res,res+cnt,cmp); cout<<cnt<<endl; for(int i=0;i<cnt;i++) { printf("%04d %d %.3lf %.3lf\n",res[i].tmin,res[i].people,res[i].cnt,res[i].averagearea); } } }