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

时间:2021-06-03 09:51:56

简单DFS。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std; struct X
{
int id;
int Father,Mother;
int k;
int son[];
int M_estate;
int Area;
}s[+];
int n;
int f[+];
struct Ans
{
int id;
int M;
int sum_set;
int sum_area;
}ans[+];
int sz;
int indx[+]; vector<int>g[+];
int min_id;
int sum;
int sum_set;
int sum_area; bool cmp(const Ans&a,const Ans&b)
{
if(1.0*a.sum_area/a.M==1.0*b.sum_area/b.M) return a.id<b.id;
return 1.0*a.sum_area/a.M>1.0*b.sum_area/b.M;
} void dfs(int x)
{
ans[sz].id=min_id;
ans[sz].M=sum;
ans[sz].sum_area=sum_area;
ans[sz].sum_set=sum_set; for(int i=;i<g[x].size();i++)
{
if(f[g[x][i]]==) continue;
f[g[x][i]]=; min_id=min(min_id,g[x][i]);
sum=sum+;
sum_set=sum_set+s[g[x][i]].M_estate;
sum_area=sum_area+s[g[x][i]].Area; dfs(g[x][i]);
}
} int main()
{
for(int i=;i<=;i++)
{
s[i].Father=-;
s[i].Mother=-;
s[i].k=;
s[i].Area=;
s[i].M_estate=;
} scanf("%d",&n);
for(int i=;i<=n;i++)
{
int ID; scanf("%d",&ID); indx[i]=ID;
s[ID].id=ID;
scanf("%d%d",&s[ID].Father,&s[ID].Mother);
scanf("%d",&s[ID].k);
for(int j=;j<s[ID].k;j++) scanf("%d",&s[ID].son[j]);
scanf("%d",&s[ID].M_estate);
scanf("%d",&s[ID].Area); if(s[ID].Father!=-){
g[s[ID].id].push_back(s[ID].Father);
g[s[ID].Father].push_back(s[ID].id);
}
if(s[ID].Mother!=-){
g[s[ID].id].push_back(s[ID].Mother);
g[s[ID].Mother].push_back(s[ID].id);
}
for(int j=;j<s[ID].k;j++)
{
g[s[ID].id].push_back(s[ID].son[j]);
g[s[ID].son[j]].push_back(s[ID].id);
}
} memset(f,,sizeof f); sz=;
for(int i=;i<=n;i++)
{
if(f[s[indx[i]].id]==) continue;
min_id=s[indx[i]].id;
sum=;
sum_set=s[indx[i]].M_estate;
sum_area=s[indx[i]].Area;
f[s[indx[i]].id]=;
dfs(s[indx[i]].id);
sz++;
} sort(ans,ans+sz,cmp);
printf("%d\n",sz);
for(int i=;i<sz;i++)
{
printf("%04d %d %.3lf %.3lf\n",ans[i].id,ans[i].M,1.0*ans[i].sum_set/ans[i].M,1.0*ans[i].sum_area/ans[i].M);
} return ;
}