This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/* There's someone in my head but it's not me */
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> pii;
#define SZ(x) (int) x.size()
#define F first
#define S second
const int N = 1e5 + 2, K = 101;
int P[N], n, k; ll ans, M[N];
vector<int> adj[N]; pii dp[N][K], pd[N][K], idp[N][K], ipd[N][K];
void merge(ll v, ll u, ll x) {
if (dp[v][x].S < max(dp[u][x].F, dp[u][x - 1].F + M[u] - P[v])) dp[v][x].S = max(dp[u][x].F, dp[u][x - 1].F + M[u] - P[v]), idp[v][x].S = u;
if (dp[v][x].F < dp[v][x].S) swap(dp[v][x].F, dp[v][x].S), swap(idp[v][x].F, idp[v][x].S);
if (pd[v][x].S < max(pd[u][x].F, pd[u][x - 1].F + M[v] - P[u])) pd[v][x].S = max(pd[u][x].F, pd[u][x - 1].F + M[v] - P[u]), ipd[v][x].S = u;
if (pd[v][x].F < pd[v][x].S) swap(pd[v][x].F, pd[v][x].S), swap(ipd[v][x].F, ipd[v][x].S);
}
void DFS(ll v, ll p = -1) {
pd[v][1].F = M[v]; ipd[v][1].F = v;
for (ll u : adj[v]) {
if (u != p) {
DFS(u, v);
for (ll i = 1; i < K; i++) {
merge(v, u, i);
}
}
}
for (ll i = 0; i <= k; i++) {
if (ipd[v][i].F == idp[v][k - i].F) ans = max({ans, pd[v][i].F + dp[v][k - i].S, pd[v][i].S + dp[v][k - i].F});
else ans = max(ans, pd[v][i].F + dp[v][k - i].F);
}
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++)
scanf("%d", &P[i]);
for (int i = 1; i < n; i++) {
int u, v; scanf("%d%d", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 1; i <= n; i++) {
for (int u : adj[i]) M[i] += P[u];
}
DFS(1);
printf("%lld\n", ans);
return 0;
}
Compilation message (stderr)
chase.cpp: In function 'int main()':
chase.cpp:41:7: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
41 | scanf("%d%d", &n, &k);
| ~~~~~^~~~~~~~~~~~~~~~
chase.cpp:43:14: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
43 | scanf("%d", &P[i]);
| ~~~~~^~~~~~~~~~~~~
chase.cpp:45:18: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
45 | int u, v; scanf("%d%d", &u, &v);
| ~~~~~^~~~~~~~~~~~~~~~
# | 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... |