struct MultiTree { int happy; std::vector<MultiTree*> sub_arr;
explicit MultiTree(int val) : happy(val) {} };
struct Elem { int ok_happy; int no_happy;
Elem(int ok_happy_, int no_happy_) : ok_happy(ok_happy_), no_happy(no_happy_) {} };
class Solution { public: int get_max_happy(const MultiTree* tree) { auto info = process(tree); return std::max(info.ok_happy, info.no_happy); }
private: Elem process(const MultiTree* tree) { if (tree->sub_arr.empty()) { return Elem(tree->happy, 0); } int ok = tree->happy; int no = 0; for (int i = 0; i < tree->sub_arr.size(); ++i) { auto info = process(tree->sub_arr[i]); ok += info.no_happy; no += std::max(info.no_happy, info.ok_happy); } return Elem(ok, no); } };
int main() { int n, root; std::cin >> n >> root; std::vector<MultiTree*> arr(n); int val; for (int i = 0; i < n; i++) { std::cin >> val; arr[i] = new MultiTree(val); } int u, v; for (int i = 1; i < n; i++) { std::cin >> u >> v; arr[u-1]->sub_arr.emplace_back(arr[v-1]); } Solution s; auto res = s.get_max_happy(arr[root-1]); std::cout << res << std::endl; return 0; }