一道并查集的应用,没什么好说的,具体见代码
#include<bits/stdc++.h>
using namespace std;
int father[10005];
struct node{
int id,M;
double AVG=0.0,AVA=0.0;
};
bool cmp(const node&n1,const node&n2){
return n1.AVA!=n2.AVA?n1.AVA>n2.AVA:n1.id<n2.id;
}
int findFather(int a){
if (father[a]==a)
return a;
int temp=findFather(father[a]);
father[a]=temp;
return temp;
}
void UnionSet(int a,int b){
int ua=findFather(a),ub=findFather(b);
if (ua!=ub)
father[max(ua,ub)]=min(ua,ub);
}
int main(){
for (int i = 0; i <= 10005; ++i) {
father[i]=i;
}
int N;
cin>>N;
unordered_map<int,pair<double,double>> m;
unordered_map<int,node> mp;
while (N--) {
int id, fatherId, momId;
cin >> id >> fatherId >> momId;
if (fatherId != -1)
UnionSet(id, fatherId);
if (momId != -1)
UnionSet(id, momId);
int k;
cin >> k;
while (k--) {
int a;
cin >> a;
UnionSet(id, a);
}
cin >> m[id].first>>m[id].second;
}
for (int j = 0; j < 10005; ++j) {
int temp=findFather(j);
if (temp!=j)
mp[temp].M++;
if (m.find(j)!=m.end()){
mp[temp].AVG+=m[j].first;
mp[temp].AVA+=m[j].second;
}
}
vector<node> v;
for (auto it=mp.begin();it!=mp.end();it++) {
(it->second).id=it->first;
++(it->second).M;
(it->second).AVA/=(it->second).M;
(it->second).AVG/=(it->second).M;
v.push_back(it->second);
}
sort(v.begin(),v.end(),cmp);
printf("%d\n",v.size());
for (int i = 0; i < v.size(); ++i) {
printf("%04d %d %.3lf %.3lf\n",v[i].id,v[i].M,v[i].AVG,v[i].AVA);
}
return 0;
}