#include <bits/stdc++.h>
using i64 = long long;
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<vector<int>> e(n);
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--;
v--;
e[u].push_back(v);
e[v].push_back(u);
}
multiset<i64> q;
vector<i64> sum(n);
i64 ans = 0;
int r;
function<void(int, int)> dfs = [&](int u, int p) {
i64 s = 0;
for (int v : e[u]) {
if (v != p) {
s += a[v];
}
}
q.insert(s);
vector<i64> b;
i64 res = 0;
for (int i = 0; i < k && !q.empty(); i++) {
i64 x = *q.rbegin();
b.push_back(x);
res += x;
q.erase(q.find(x));
}
ans = max(ans, res + sum[u] - a[r]);
for (i64 x : b) {
q.insert(x);
}
for (int v : e[u]) {
if (v != p) {
sum[v] = sum[u] + a[v];
q.erase(q.find(s));
q.insert(s - a[v] - a[v]);
dfs(v, u);
q.erase(q.find(s - a[v] - a[v]));
q.insert(s);
}
}
q.erase(q.find(s));
};
for (int i = 0; i < n; i++) {
sum[i] = a[i];
r = i;
dfs(i, -1);
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}
/*
12 2
2 3 3 8 1 5 6 7 8 3 5 4
2 1
2 7
3 4
4 7
7 6
5 6
6 8
6 9
7 10
10 11
10 12
*/
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
212 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
212 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
4024 ms |
71276 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
212 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |