PTA-L2-007 Family Real Estate (25 points)

PTA-L2-007 Family Real Estate (25 points)

Portal

This question is simple and checked. It's just that the output processing is a little troublesome.

We put the individual's id as the index of the array. Then store, after merging, use the set container to store the id of the representative of each family, and then store it in the structure accordingly, and then sort it.

code part:

#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;
} 

Guess you like

Origin blog.csdn.net/qq_44624316/article/details/110186940