题意
给出n行信息,每行信息包括id,父母id,孩子id和自己拥有的estate和area。
统计每个家族的平均estate和平均area,按照平均area降序输出(重复则按照id升序)。将家族中的id最小成员的id作为家族的id。
思路
并查集。要注意的是最小id优先作为首领的处理。
Sample Input:
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
Sample output:
3
8888 1 1.000 1000.000
0001 15 0.600 100.000
5551 4 0.750 100.000
#include "bits/stdc++.h"
using namespace std;
const int N = 10010;
int father[N];
int findFather(int x){
int v = x;
while (father[x] != x) x = father[x];
while (v != x){
int t = v;
v = father[v];
father[t] = x;
}
return x;
}
void _union(int id1,int id2){
int f1 = findFather(id1), f2 = findFather(id2);
father[max(f1,f2)] = min(f1,f2);
}
int main(){
// freopen("input.txt","r",stdin);
for (int i = 0; i <N; ++i) father[i] = i;
int n; cin >> n;
unordered_map<int,double> setsMap,areaMap;
set<int> ids;
for (int i = 0; i < n; ++i) {
int id,f1,f2,k; scanf("%d%d%d%d",&id,&f1,&f2,&k);
ids.insert(id);
if (f1 != -1) _union(f1,id),ids.insert(f1);
if (f2 != -1) _union(f2,id), ids.insert(f2);
for (int j = 0; j < k; ++j) {
int child; scanf("%d",&child); ids.insert(child);
_union(child,id);
}
double t1,t2; scanf("%lf%lf",&t1,&t2);
setsMap[id] += t1; areaMap[id] += t2;
}
struct Node{
int id{INT32_MAX};
int m{0};
double sets{0};
double area{0};
};
unordered_map<int,Node> group;
for(int id:ids) {
int head = findFather(id);
group[head].id = head;
group[head].m ++;
group[head].sets += setsMap[id];
group[head].area += areaMap[id];
}
cout << group.size() << endl;
vector<Node*> ans;
for(auto &item:group) {
Node* p = &item.second;
p->sets /= p->m, p->area /= p->m;
ans.push_back(p);
}
sort(ans.begin(),ans.end(),[](Node* p1,Node* p2){
if (p1->area == p2->area) return p1->id < p2->id;
return p1->area > p2->area;
});
for(auto p:ans) printf("%04d %d %.3f %.3f\n",p->id,p->m,p->sets,p->area);
}