이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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] - subarborele lui i daca mai am j de aruncat
*/
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;
if (n <= 1000) {
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]);
}
} else {
dfs(1, 0);
ans = dp[1][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... |