PTA-L2-007 家庭房产 (25分)

PTA-L2-007 家庭房产 (25分)

传送门

这道题,简单并查集。就是输出处理麻烦了些许。

我们把个人的id作为数组的下标。然后进行存储,合并好之后,用set容器把每个家庭的代表的id存起来,然后相应的存入到结构体中,然后sort一下即可。

代码部分:

#include <bits/stdc++.h>
#define mst(a, n) memset(a, n, sizeof(a))
using namespace std;
const int N = 1e4+ 10;
const int M = 55;
const int INF = 1e6 + 10;
typedef long long ll;

struct node
{
    
    
	int num;
	int peo;
	double sumh;
	double sumare;
}a[N];
int n;
int id, fath, moth, k, chi;
int fa[N];
int vis[N];
int cnt[N];
int area[N];
int sum[N];

int find(int x)
{
    
    
	if (x != fa[x])
	{
    
    
		return fa[x] = find(fa[x]);
	}
	return fa[x];
}

void merge(int x, int y)
{
    
    
	int fax = find(x);
	int fay = find(y);
	if (fax > fay)
	{
    
    
		fa[fax] = fay;
	}
	else
	{
    
    
		fa[fay] = fax;
	}
}

bool cmp(node x, node y)
{
    
    
	if (x.sumare == y.sumare)
	{
    
    
		return x.num < y.num;
	}
	return x.sumare > y.sumare;
}

int main()
{
    
    
	for (int i = 0; i < N; i++)
	{
    
    
		fa[i] = i;
	}
	cin >> n;
	for (int i = 0; i < n; i++)
	{
    
    
		cin >> id >> fath >> moth >> k;
		vis[id] = 1;
		if (fath != -1)
		{
    
    
			vis[fath] = 1;
			merge(id, fath);
		}
		if (moth != -1)
		{
    
    
			vis[moth] = 1;
			merge(id, moth);
		}
		for (int j = 0; j < k; j++)
		{
    
    
			int child;
			cin >> child;
			vis[child] = 1;
			merge(id, child);
		}
		cin >> cnt[id] >> area[id];
	}
	set<int> st;
	for (int i = 0; i < N; i++)
	{
    
    
		if (!vis[i])
		{
    
    
			continue;
		}
		int root = find(i);
		sum[root]++;
		if (root != i)
		{
    
    
			cnt[root] += cnt[i];
			area[root] += area[i];
		}
		st.insert(root);
	}
	int count = 0;
	set<int>::iterator it = st.begin();
	while (it != st.end())
	{
    
    
		int root = *it;
		a[count].num = root;
		a[count].peo = sum[root];
		a[count].sumare = 1.0 * area[root] / sum[root];
		a[count++].sumh = 1.0 * cnt[root] / sum[root];
		it++;
	}
	sort(a, a + count, cmp);
	cout << count << endl;
	for (int i = 0; i < count; i++)
	{
    
    
		printf ("%04d %d %.3f %.3f\n", a[i].num, a[i].peo, a[i].sumh, a[i].sumare);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_44624316/article/details/110186940