# include <stdio.h># include <algorithm># include <string.h>using namespace Std;int father[1010];int next[1010];//the next element of the current collection (contains i) int pre[1010];//The last element of the current collection (contains i) int num[1010];//num[i] The number of points stored in the current collection (including i) int vis[1010];int sum[1010];//the element of the current collection and the cost of an int c[1010];//point int n,r;int Find_max ()//finds the largest collection of current weights {double max=0;int bh=-1;for (int i=1;i<=n ; i++) {if (max< (sum[i]*1.0)/num[i]&&!vis[i]) {max= (sum[i]*1.0)/num[i];bh=i;}} return BH;} void Uni (int x)//union {int I;for (i=father[x];p re[i]!=-1;i=pre[i])//Find the collection where the parent element is located {}sum[i]+=sum[x]; Num[i]+=num[x];for (I=father[x];next[i]!=-1;i=next[i])//Find the base element of the collection where the parent element {}next[i]=x;pre[x]=i;vis[x]=1;} int main () {int i;while (~scanf ("%d%d", &n,&r), N+r) {for (i=1;i<=n;i++) {scanf ("%d", &c[i]); vis[i]=0;sum [I]=c[i];p re[i]=next[i]=-1;num[i]=1;} for (i=1;i<n;i++) {int a,b;scanf ("%d%d", &a,&b); father[b]=a;} int d;vis[r]=1;//initial point while (1) {D=find_max (); if (d==-1) Break;uni (d);} int ans=0,t=1;for (I=r;i!=-1;i=next[i]) {ans+=c[i]*t;t++;} printf ("%d\n", ans);} return 0;}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
POJ 2054 Color a Tree (greedy)