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;
using ll = long long;
#define int ll
#define endl '\n'
#define pb push_back
using pi = pair<int, int>;
template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
/*
dp[i][j][0/1] - subarborele lui i daca mai am j de aruncat si l-am colectat sau nu pe i
*/
const int INF = 1e16;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, k;
cin >> n >> k;
vector<int> a(n + 1);
for (int i = 1; i <= n; ++i) cin >> a[i];
vector<vector<int>> adj(n + 1);
for (int i = 1; i < n; ++i) {
int u, v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
vector<vector<int>> dp(n + 1, vector<int>(k + 1));
function<void(int, int)> dfs = [&](int u, int p) {
int S = 0;
for (int v : adj[u]) {
if (v == p) continue;
dfs(v, u);
S += a[v];
}
for (int v : adj[u]) {
if (v == p) continue;
for (int i = 0; i <= k; ++i) {
// colectez
if (i > 0) dp[u][i] = max(dp[u][i], S + max(dp[v][i - 1], 0LL));
// nu colectez
dp[u][i] = max(dp[u][i], dp[v][i]);
}
}
};
int ans = 0;
for (int r = 1; r <= n; ++r) {
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= k; ++j) dp[i][j] = -INF;
}
dfs(r, 0);
ans = max(ans, dp[r][k]);
}
cout << ans;
}
# | 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... |