【天梯赛】家庭房产 (25 分)

原题链接

题解:又一道并查集

#include<bits/stdc++.h>
using namespace std;
const int N=1e4+10;
int pre[N];
bool ex[N];
struct node{
	int id=-1;
	int num;
	double house=0;
	double are=0;
};
int n;
int root(int x)
{
	while(pre[x]!=x) x=pre[x];
	return x;
}
void un(int x,int y)
{
	int rootx=root(x);
	int rooty=root(y);
	if(rootx<rooty) pre[rooty]=rootx;
	else pre[rootx]=rooty;
}
bool cmp(node x,node y)
{
	if(x.are/x.num==y.are/y.num) return x.id<y.id;
	else return x.are/x.num>y.are/y.num;
}
int main()
{
	for(int i=0;i<10000;i++) pre[i]=i; 
	node arr[10000];
	cin>>n;
	for(int i=0;i<n;i++)
	{
		int id,fa,ma;
		cin>>id>>fa>>ma;
		arr[id].id=id;
		ex[id]=1;
		if(fa!=-1) ex[fa]=1,un(id,fa);
		if(ma!=-1) ex[ma]=1,un(id,ma); 
		int k,x;
		cin>>k;
		while(k--)
		{
			cin>>x;
			un(id,x);
			ex[x]=1;
		}
		cin>>arr[id].house>>arr[id].are;
	}
	node tmp[10000];
	for(int i=0;i<10000;i++)
	{
		if(ex[i])
		{
			int f=root(i);//改变好所在家庭的最小编号 
			tmp[f].id=f;
			tmp[f].num++;
			if(arr[i].id!=-1)//该编号有房子 
			{
				tmp[f].house+=arr[i].house;
				tmp[f].are+=arr[i].are;
			}
		}
	}
	node res[10000];
	int i=0;
	for(int j=0;j<10000;j++)
	{
		if(tmp[j].id!=-1) res[i++]=tmp[j];
	}
	sort(res,res+i,cmp);
	cout<<i<<endl;
	for(int j=0;j<i;j++)
	{
		printf("%04d %d %.3f %.3f\n",res[j].id,res[j].num,res[j].house/res[j].num,res[j].are/res[j].num);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值