PAT A1114 Family Property

Posted zhanglichen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT A1114 Family Property相关的知识,希望对你有一定的参考价值。

 

用并查集处理每个家庭的信息,注意标记~

#include<bits/stdc++.h>
using namespace std;
const int maxn=10010;
bool visit[maxn]={false};
int N;
struct node {
    int id;
    int child[105];
    double num;
    double area;
}Node[maxn];
struct family {
    int id;
    double num;
    double area;
    int renshu;
}f[maxn];
int father[maxn];
void init () {
    for (int i=0;i<maxn;i++)
    father[i]=i;
}
int findfather (int x) {
    int a=x;
    while (x!=father[x])
    x=father[x];
    while (a!=father[a]) {
        int z=a;
        a=father[a];
        father[z]=x;
    }
    return x;
}
void Union (int a,int b) {
    int faA=findfather (a);
    int faB=findfather (b);
    if (faA<faB) father[faB]=faA;
    else father[faA]=faB;
};
bool cmp (family a,family b) {
    if (a.area!=b.area) return a.area>b.area;
    else return a.id<b.id;
}
int main () {
    scanf ("%d",&N);
    int id,fatherid,motherid,k;
    double num,area;
    init ();
    for (int i=0;i<N;i++) {
        scanf ("%d %d %d %d",&id,&fatherid,&motherid,&k);
        Node[i].id=id;
        visit[id]=true;
        if (fatherid!=-1) {
            visit[fatherid]=true;
            Union (id,fatherid);
        }
        if (motherid!=-1) {
            visit[motherid]=true;
            Union (id,motherid);
        }
        for (int j=0;j<k;j++) {
            scanf ("%d",&Node[i].child[j]);
            visit[Node[i].child[j]]=true;
            Union (id,Node[i].child[j]);
        }
        scanf ("%lf %lf",&Node[i].num,&Node[i].area);
    }
    for (int i=0;i<N;i++) {
        f[findfather(Node[i].id)].area+=Node[i].area;
        f[findfather(Node[i].id)].num+=Node[i].num;
    }
    int ans=0;
    for (int i=0;i<maxn;i++) {
        if (visit[i]==true) {
            f[findfather(i)].renshu++;
            f[findfather(i)].id=findfather(i);
        }
    }
    for (int i=0;i<maxn;i++)
    if (f[i].renshu!=0) {
        ans++;
        f[i].area/=f[i].renshu;
        f[i].num/=f[i].renshu;
    }
    sort (f,f+maxn,cmp);
    printf ("%d
",ans);
    for (int i=0;i<ans;i++) {
        printf ("%04d %d %.3f %.3f
",f[i].id,f[i].renshu,f[i].num,f[i].area);
    }
    return 0;
}

 

以上是关于PAT A1114 Family Property的主要内容,如果未能解决你的问题,请参考以下文章

[PAT] A1114 Family Property

A1114 Family Property (25分)

A1114 Family Property (25分)

PAT_A1114#Family Property

PAT 1114 Family Property[并查集][难]

PAT (Advanced Level) 1114. Family Property (25)