1114 Family Property(并查集)
Posted keep23456
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1114 Family Property(并查集)相关的知识,希望对你有一定的参考价值。
题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805356599820288
题目比较麻烦,因为限时200ms,所以要用散列。
1 #include<iostream> 2 #include<vector> 3 #include<unordered_map> 4 #include<algorithm> 5 using namespace std; 6 7 struct Node { 8 int id,num; 9 double AVGS = 0,AVGA = 0; 10 bool flag = false; 11 }; 12 13 int father[10000]; 14 void init() { 15 for(int i = 0; i < 10000; ++i) 16 father[i] = i; 17 } 18 19 int findfather(int a) { 20 int b = a; 21 while(a != father[a]) 22 a = father[a]; 23 while(b != father[b]) { 24 int t = b; 25 b = father[b]; 26 father[t] = a; 27 } 28 return a; 29 } 30 31 void Union(int a,int b) { 32 int fa = findfather(a); 33 int fb = findfather(b); 34 if(fa != fb) 35 father[max(fa,fb)] = min(fa,fb); 36 } 37 bool cmp(const Node& a ,const Node& b) { 38 if(a.flag != b.flag) return a.flag > b.flag; 39 if(a.AVGA /a.num != b.AVGA/b.num ) return a.AVGA /a.num > b.AVGA/b.num; 40 return a.id < b.id; 41 } 42 43 int main() { 44 init(); 45 int n; 46 cin>>n; 47 unordered_map<int,vector<int> > mp1;//记录当前ID的信息 48 unordered_map<int,int> mp2; //记录所有ID 49 for(int i = 0; i < n; ++i) { 50 int id,fa,mo,k,child,estate,area; 51 scanf("%d%d%d%d",&id,&fa,&mo,&k); 52 mp2[id] = 1; 53 if(fa != -1) Union(id,fa),mp2[fa] = 1; 54 if(mo != -1) Union(id,mo),mp2[mo] = 1; 55 for(int j = 0; j < k; ++j) { 56 scanf("%d",&child); 57 Union(id,child); 58 mp2[child] = 1; 59 } 60 scanf("%d%d",&estate,&area); 61 mp1[id].push_back(estate); 62 mp1[id].push_back(area); 63 } 64 vector<Node> v(10000); 65 int cnt = 0; 66 for(auto it:mp2) { 67 int fa = findfather(it.first); 68 v[fa].id = fa; 69 v[fa].num++; 70 if(v[fa].num == 1) cnt++; //统计不同家庭的个数 71 if(mp1.count(it.first)) { 72 v[fa].AVGS += mp1[it.first][0]; 73 v[fa].AVGA += mp1[it.first][1]; 74 } 75 v[fa].flag = true; 76 } 77 sort(v.begin(),v.end(),cmp); 78 printf("%d ",cnt); 79 for(int i = 0; i < cnt; ++i) { 80 printf("%04d %d %.3f %.3f ",v[i].id,v[i].num,v[i].AVGS/v[i].num,v[i].AVGA/v[i].num); 81 } 82 return 0; 83 }
以上是关于1114 Family Property(并查集)的主要内容,如果未能解决你的问题,请参考以下文章
1114 Family Property (25 分)难度: 中/ 知识点: 并查集