This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
const int mxN = 505;
int n, m;
int a[mxN];
vector<int> adj[mxN];
long long dp[mxN][mxN][2];
void dfs(int u, int p = -1) {
  dp[u][1][0] = 0;
  for (auto &to: adj[u]) {
    if (to != p) {
      dfs(to, u);
      for (int i = m; i; i--) {
        auto &res = dp[u][i][0];
        auto &res2 = dp[u][i][1];
        for (int j = 0; j < i; j++) {
          if (i - j > 2) {
            res = max(res, dp[u][i - j - 3][0] + dp[to][j][1]);
            //res2 = max(res2, dp[u][i - j - 3][1] + dp[to][j][1] + a[u]);
          }
          if (i - j > 1) {
            //res = max(res, dp[u][i - j - 2][1] + dp[to][j][0] + a[u]);
            res = max(res, dp[u][i - j - 2][0] + dp[to][j][1]);
            res2 = max(res2, dp[u][i - j - 2][1] + dp[to][j][1]);
          }
          //if (i > j) {
            res = max(res, dp[u][i - j - 1][1] + dp[to][j][0]);
          //}
        }
      }
    }
  }
  for (int i = m; i; i--) {
    for (bool j: {0, 1}) {
      dp[u][i][j] = max(dp[u][i][j], dp[u][i - 1][j] + a[u]);
    }
  }
}
int main() {
  cin.tie(0)->sync_with_stdio(0);
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  for (int i = 1, x, y; i < n; i++) {
    cin >> x >> y; x--; y--;
    adj[x].push_back(y);
    adj[y].push_back(x);
  }
  dfs(0);
  long long res = 0;
  for (int i = 1; i <= m; i++) {
    res = max(res, dp[0][i][0]);
  }
  cout << res << "\n";
  return 0;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |