第十章 并查集 2 AcWing 1604. 家产
原题链接
算法标签
并查集
思路
将关系信息读入存储, 依题意合并
存储数组含义
依题意合并操作
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include<bits/stdc++.h>
#define int long long
#define xx first
#define yy second
#define ump unordered_map
#define us unordered_set
#define pq priority_queue
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>=b;--i)
using namespace std;
typedef pair<int, int> PII;
const int N=10005, inf=0x3f3f3f3f3f3f3f3f, mod=1e9+7;
const double Exp=1e-8;
//int t, n, m, cnt, ans;
int n, p[N], c[N], hc[N], ha[N], m, k, kk, id, f, mo;
bool st[N];
struct Ed{
int a, b;
}e[N];
struct Fam{
int id, c, hc, ha;
bool operator<(const Fam &t) const{
if(ha*t.c!=t.ha*c){
return ha*t.c>t.ha*c;
}
return id<t.id;
}
};
inline int rd(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
int find(int x){
if(x!=p[x]){
return p[x]=find(p[x]);
}
return p[x];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
n=rd();
m=0;
while(n--){
id=rd(), f=rd(), mo=rd();
st[id]=true;
if(f!=-1){
e[m++]={id, f};
}
if(mo!=-1){
e[m++]={id, mo};
}
k=rd();
while(k--){
kk=rd();
e[m++]={id, kk};
}
hc[id]=rd(), ha[id]=rd();
}
rep(i, 0, N){
p[i]=i;
c[i]=1;
}
rep(i, 0, m){
int a=e[i].a, b=e[i].b;
st[a]=st[b]=true;
int pa=find(a), pb=find(b);
if(pa!=pb){
if(pa<pb){
swap(pa, pb);
}
c[pb]+=c[pa];
hc[pb]+=hc[pa];
ha[pb]+=ha[pa];
p[pa]=pb;
}
}
vector<Fam> fam;
rep(i, 0, N){
if(st[i]&&p[i]==i){
fam.push_back({i, c[i], hc[i], ha[i]});
}
}
sort(fam.begin(), fam.end());
printf("%lld\n", fam.size());
for(auto x:fam){
printf("%04lld %lld %.3lf %.3lf\n", x.id, x.c, (double)x.hc/x.c, (double)x.ha/x.c);
}
return 0;
}
参考文献
AcWing 1604. 家产(PAT甲级辅导课)y总视频讲解
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈