# Include <stdio. h> # include <algorithm> # include <string. h> using namespace STD; int father [1010]; int next [1010]; // The next element of the current set (including I) int pre [1010]; // The last element of the current set (including I) int num [1010]; // num [I] the number of points stored in the current set (including I) int vis [1010]; int sum [1010]; // the elements of the current set and int c [1010]; // the consumption of int N, R; int find_max () // find the set with the maximum current weight {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]; Pre [I]! =-1; I = pre [I]) // find the set 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 set where the parent element is located {} next [I] = x; Pre [x] = I; vis [x] = 1;} int main () {int I; while (~ Scanf ("% d", & N, & R), N + r) {for (I = 1; I <= N; I ++) {scanf ("% d", & C [I]); vis [I] = 0; sum [I] = C [I]; pre [I] = next [I] =-1; num [I] = 1 ;}for (I = 1; I <n; I ++) {int, b; scanf ("% 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 ;}
Poj 2054 color a tree (Greedy)