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;
#define all(v) v.begin(), v.end()
typedef long long ll;
const int NMAX = 1e5 + 5;
ll n, k, a[NMAX], x, y, u[NMAX][105], d[NMAX][105], ans;
vector<int> adj[NMAX];
void dfs(int x, int bef){
ll sum = 0;
for(int nx : adj[x]) sum += a[nx];
u[x][1] = sum;
for(int nx : adj[x]){
if(nx == bef) continue;
dfs(nx, x);
for(int i = 1; i <= k; i++){
ans = max(ans, u[x][i] + d[nx][k - i]);
u[x][i] = max({u[x][i], u[x][i - 1], u[nx][i], u[nx][i - 1] + sum - a[nx]});
d[x][i] = max({d[x][i], d[x][i - 1], d[nx][i], d[nx][i - 1] + sum - a[bef]});
}
}
reverse(all(adj[x]));
memset(u[x], 0, sizeof(u[x]));
memset(d[x], 0, sizeof(d[x]));
u[x][1] = sum;
for(int nx : adj[x]){
if(nx == bef) continue;
for(int i = 1; i <= k; i++){
ans = max(ans, u[x][i] + d[nx][k - i]);
u[x][i] = max({u[x][i], u[x][i - 1], u[nx][i], u[nx][i - 1] + sum - a[nx]});
d[x][i] = max({d[x][i], d[x][i - 1], d[nx][i], d[nx][i - 1] + sum - a[bef]});
}
}
return;
}
int main(void){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 0; i < n - 1; i++){
cin >> x >> y;
adj[x].emplace_back(y);
adj[y].emplace_back(x);
}
dfs(1, 0);
cout << ans;
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... |