简单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[10]; int M_estate; int Area; }s[10000+10]; int n; int f[10000+10]; struct Ans { int id; int M; int sum_set; int sum_area; }ans[10000+10]; int sz; int indx[10000+10]; vector<int>g[10000+10]; 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=0;i<g[x].size();i++) { if(f[g[x][i]]==1) continue; f[g[x][i]]=1; min_id=min(min_id,g[x][i]); sum=sum+1; 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=0;i<=10000;i++) { s[i].Father=-1; s[i].Mother=-1; s[i].k=0; s[i].Area=0; s[i].M_estate=0; } scanf("%d",&n); for(int i=1;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=0;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!=-1){ g[s[ID].id].push_back(s[ID].Father); g[s[ID].Father].push_back(s[ID].id); } if(s[ID].Mother!=-1){ g[s[ID].id].push_back(s[ID].Mother); g[s[ID].Mother].push_back(s[ID].id); } for(int j=0;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,0,sizeof f); sz=0; for(int i=1;i<=n;i++) { if(f[s[indx[i]].id]==1) continue; min_id=s[indx[i]].id; sum=1; sum_set=s[indx[i]].M_estate; sum_area=s[indx[i]].Area; f[s[indx[i]].id]=1; dfs(s[indx[i]].id); sz++; } sort(ans,ans+sz,cmp); printf("%d\n",sz); for(int i=0;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 0; }
时间: 2024-10-09 16:23:27