#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second
const ll inf = 1e18;
const int N = 1e5;
const int K = 100;
ll dp[N + 1][K + 1][2];
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k; cin>>n>>k;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++){
cin>>a[i];
}
vector<int> g[n + 1];
for (int i = 1; i < n; i++){
int x, y; cin>>x>>y;
g[x].pb(y);
g[y].pb(x);
}
vector<ll> s(n + 1);
for (int i = 1; i <= n; i++){
s[i] = a[i];
for (int j: g[i]){
s[i] += a[j];
}
}
ll out = 0;
function<void(int, int)> fill = [&](int v, int pr){
for (int i: g[v]){
if (i == pr) continue;
fill(i, v);
}
for (int x = 1; x <= k; x++){
dp[v][x][0] = dp[v][x][1] = -inf;
for (int i: g[v]){
if (i == pr) continue;
dp[v][x][0] = max(dp[v][x][0], (s[v] - a[v]) + dp[i][x - 1][0] - a[v]);
dp[v][x][0] = max(dp[v][x][0], s[v] + dp[i][x - 1][1] - a[v]);
dp[v][x][1] = max(dp[v][x][1], dp[i][x][0] - a[v]);
}
if (x == 1) dp[v][1][0] = s[v] - a[v];
out = max(out, dp[v][x][0]);
out = max(out, dp[v][x][1]);
}
};
if (n <= 1000){
for (int i = 1; i <= n; i++){
fill(i, 0);
}
}
else {
fill(1, 0);
}
cout<<out<<"\n";
}
# | 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... |