Skip to content

Instantly share code, notes, and snippets.

@Hacv16
Last active September 28, 2023 23:03
Show Gist options
  • Save Hacv16/39e7b2bbcac4a3a5d2994780a1707f5d to your computer and use it in GitHub Desktop.
Save Hacv16/39e7b2bbcac4a3a5d2994780a1707f5d to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
#define int long long int
const int MAX = 2e5 + 10;
const int MAXK = 210;
const int INF = 1e18 + 10;
int n, k, timer, dp[MAX][MAXK], v[MAX], sub[MAX], tin[MAX], tout[MAX];
vector<int> adj[MAX], order;
void dfs(int u, int p)
{
tin[u] = ++timer;
order.push_back(u);
sub[u] = v[u];
for(auto v : adj[u]){
if(v == p) continue;
dfs(v, u);
sub[u] += sub[v];
}
tout[u] = timer;
}
int32_t main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> v[i];
for(int i = 1; i < n; i++){
int u, v; cin >> u >> v;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
dfs(1, -1);
for(int i = 1; i <= k; i++)
dp[n + 1][i] = INF;
dp[n + 1][0] = 0;
for(int i = n; i >= 1; i--){
int u = order[i - 1];
for(int j = 0; j <= k; j++){
dp[i][j] = dp[i + 1][j];
if(j > 0) dp[i][j] = min(dp[i][j], dp[ tout[u] + 1][j - 1] + sub[u]);
}
}
int ans = 0;
for(int i = 0; i <= k; i++)
ans = min(ans, dp[1][i]);
cout << sub[1] - ans << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment