#include <bits/stdc++.h>
using namespace std;
#define all(x) x.begin(), x.end()
#define ar array
#define pb push_back
#define ln '\n'
#define int long long
using i64 = long long;
template <class F, class _S>
bool chmin(F &u, const _S &v){
bool flag = false;
if ( u > v ){
u = v; flag |= true;
}
return flag;
}
template <class F, class _S>
bool chmax(F &u, const _S &v){
bool flag = false;
if ( u < v ){
u = v; flag |= true;
}
return flag;
}
#define P pair <int,int>
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, k; cin >> n >> k;
vector <int> a(n);
for ( auto &u: a ) cin >> u;
vector <vector<int>> G(n);
for ( int i = 1; i < n; i++ ){
int u, v; cin >> u >> v;
--u, --v;
G[u].pb(v), G[v].pb(u);
}
vector <int> s(n);
for ( int i = 0; i < n; i++ ){
for ( auto &v: G[i] ){
s[i] += a[v];
}
}
vector <vector<pair<int,int>>> L(n, vector <pair<int,int>> (k + 1, {0, -1})), R(n, vector <pair<int,int>> (k + 1, {0, -1}));
auto dfs = [&](auto dfs, int u, int p) -> void{
for ( auto &v: G[u] ){
if ( v == p ) continue;
dfs(dfs, v, u);
for ( int j = 0; j <= k; j++ ){
for ( auto nj: {j, j + 1} ){
if ( nj > k ) continue;
for ( auto nw: {L[v][j]} ){
nw.first += (nj - j) * (s[v] - a[u]);
chmax(L[u][nj], nw);
continue;
if ( L[u][nj].first < nw.first ){
swap(R[u][nj], L[u][nj]);
L[u][nj] = nw;
} else if ( L[u][nj].second == R[u][nj].second || (nw.first > R[u][nj].first && nw.second != L[u][nj].second) ){
R[u][nj] = nw;
}
}
}
}
}
};
dfs(dfs, 0, -1);
int opt = 0;
for ( int i = 0; i <= k; i++ ){
chmax(opt, L[0][i].first + s[0]);
}
cout << opt;
cout << '\n';
}
/*
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 |
0 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
0 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
271 ms |
342272 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
0 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |