structNode { int id = -1; int score = 0; bool visited = false; vector<Node*> successors; };
classTree { private: Node* root; int** F; int N, M;
voidtraverseTree(Node* node){ node->visited = true; for (int i = 0; i < node->successors.size(); i++) if (!node->successors[i]->visited) traverseTree(node->successors[i]);
F[node->id][1] = node->score; for (int i = 0; i < node->successors.size(); i++) { if (!node->successors[i]->visited) { for (int j = M; j >= 2; j--) { for (int k = 1; k < j; k++) F[node->id][j] = max(F[node->id][j], F[node->id][j - k] + F[node->successors[i]->id][k]); } } }
node->visited = false; }
public: Tree(Node* node, int n, int m) { N = n; M = m; root = node; F = newint*[N + 1]; for (int i = 0; i < N + 1; i++) { F[i] = newint[M + 1]; for (int j = 0; j < M + 1; j++) F[i][j] = 0; } }
~Tree() { for (int i = 0; i < N; i++) delete[] F[i]; delete[] F; }
intmain(){ int N = 0, M = 0; cin >> N >> M; Node* nodes = new Node[N + 1]; for (int i = 1; i < N + 1; i++) { int s = 0; cin >> s; nodes[i].id = i; nodes[i].score = s; } for (int i = 0; i < N - 1; i++) { int a = 0, b = 0; cin >> a >> b; nodes[a].successors.push_back(nodes + b); nodes[b].successors.push_back(nodes + a); } Tree tree = Tree(nodes + 1, N, M);