#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
using ll = long long;
const int N = 1e5+5;
template<class X, class Y>
bool cmax(X &a, const Y &b) {
return a < b ? a = b, 1 : 0;
}
//--------------------------------------
int n, k, a[N];
vector<int> adj[N];
ll f[N][105][3];
void dfs(int u, int pr) {
ll s = 0;
for (auto v : adj[u]) if (v != pr) {
dfs(v, u);
s += a[v];
}
f[u][0][0] = f[u][1][2] = 0;
for (auto v : adj[u]) if (v != pr) {
for (int i = 0; i <= k; i++) {
cmax(f[u][i][0], max(f[v][i][0], f[v][i][1]));
cmax(f[u][i][1], f[v][i][2] + a[u]);
if (i) {
cmax(f[u][i][2], f[v][i-1][0] + s);
cmax(f[u][i][2], f[v][i-1][1] + s - a[v]);
cmax(f[u][i][2], f[v][i-1][2] + s - a[v] + a[u]);
}
}
}
for (int i = 1; i <= k; i++) {
for (int j = 0; j < 3; j++)
cmax(f[u][i][j], f[u][i-1][j]);
}
}
int main() {
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 = 1; i < n; i++) {
int u, v; cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
ll ans = 0;
for (int root = 1; root <= (n > 1e3 ? 1 : n); root++) {
for (int i = 1; i <= n; i++) {
memset(f[i], -63, sizeof(f[i]));
}
dfs(root, root);
ans = max({ans, f[root][k][0], f[root][k][1], f[root][k][2]});
}
cout << ans;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
2904 KB |
Output is correct |
2 |
Correct |
1 ms |
2908 KB |
Output is correct |
3 |
Correct |
1 ms |
2916 KB |
Output is correct |
4 |
Correct |
1 ms |
2904 KB |
Output is correct |
5 |
Correct |
1 ms |
2904 KB |
Output is correct |
6 |
Correct |
1 ms |
2904 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
2904 KB |
Output is correct |
2 |
Correct |
1 ms |
2908 KB |
Output is correct |
3 |
Correct |
1 ms |
2916 KB |
Output is correct |
4 |
Correct |
1 ms |
2904 KB |
Output is correct |
5 |
Correct |
1 ms |
2904 KB |
Output is correct |
6 |
Correct |
1 ms |
2904 KB |
Output is correct |
7 |
Incorrect |
623 ms |
7312 KB |
Output isn't correct |
8 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
141 ms |
257608 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
2904 KB |
Output is correct |
2 |
Correct |
1 ms |
2908 KB |
Output is correct |
3 |
Correct |
1 ms |
2916 KB |
Output is correct |
4 |
Correct |
1 ms |
2904 KB |
Output is correct |
5 |
Correct |
1 ms |
2904 KB |
Output is correct |
6 |
Correct |
1 ms |
2904 KB |
Output is correct |
7 |
Incorrect |
623 ms |
7312 KB |
Output isn't correct |
8 |
Halted |
0 ms |
0 KB |
- |