제출 #583262

#제출 시각아이디문제언어결과실행 시간메모리
583262600MihneaChase (CEOI17_chase)C++17
40 / 100
1312 ms524288 KiB
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const int N = (int) 1e5 + 7;
const int B = 100 + 7;
const ll INF = (ll) 1e18 + 7;
int n, bread_have, pigs[N];
ll gain[N];
ll dp[N][B];
ll sol = -INF;
vector<int> g[N];
multiset<ll> s[N][B];

void compute(int a, int p) {
  for (int i = 0; i <= bread_have; i++) {
    s[a][i].clear();
    s[a][i].insert(0);
  }
  gain[a] = 0;
  for (auto &b : g[a]) {
    if (b != p) {
      gain[a] += pigs[b];
      for (int i = 1; i <= bread_have; i++) {
        s[a][i].insert(-dp[b][i]);
      }
    }
  }
  for (int i = bread_have; i >= 0; i--) {
    dp[a][i] = -*s[a][i].begin();
    if (i + 1 <= bread_have) {
      dp[a][i + 1] = max(dp[a][i + 1], dp[a][i] + gain[a]);
    }
  }
}



void dfs(int a, int p = 0) {
  for (auto &b : g[a]) {
    if (b != p) {
      dfs(b, a);
    }
  }

  compute(a, p);
}

void reroot(int a, int p) {
  compute(a, p);
  compute(p, 0);
}

void solve(int a, int p = 0) {
  sol = max(sol, dp[a][bread_have]);
  for (auto &b : g[a]) {
    if (b != p) {
      reroot(a, b);
      solve(b, a);
      reroot(b, a);
    }
  }
}

signed main() {
  ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

///  freopen ("input.txt", "r", stdin);

  cin >> n >> bread_have;
  for (int i = 1; i <= n; i++) {
    cin >> pigs[i];
    for (int j = 1; j <= bread_have; j++) {
      s[i][j].insert(0);
    }
  }

  for (int i = 1; i < n; i++) {
    int a, b;
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs(1);
  solve(1);
  cout << sol << "\n";
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...