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;
#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;
}
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 = 0; i + 1 < 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<multiset<int>>> dp(n, vector <multiset<int>> (k + 1));
for ( int i = 0; i < n; i++ ){
for ( int j = 0; j <= k; j++ ){
dp[i][j].insert(0);
}
}
auto er = [&](auto &s, int u){
s.erase(s.find(u));
};
auto get = [&](int v, int j, int u){
return max(*dp[v][j].rbegin(), (j > 0 ? *dp[v][j - 1].rbegin() + s[v] - a[u] : 0));
};
auto dfs = [&](auto dfs, int u, int p) -> void{
for ( auto &v: G[u] ){
if ( v != p ){
dfs(dfs, v, u);
for ( int j = 0; j <= k; j++ ){
dp[u][j].insert(get(v, j, u));
}
}
}
};
dfs(dfs, 0, -1);
int opt = 0;
auto dfs2 = [&](auto dfs2, int u, int p) -> void{
for ( int j = 1; j <= k; j++ ){
chmax(opt, *dp[u][j - 1].rbegin() + s[u]);
}
if ( n > 1e3 ) return;
for ( auto &v: G[u] ){
if ( v == p ) continue;
for ( int j = 0; j <= k; j++ ){
er(dp[u][j], get(v, j, u));
}
for ( int j = 0; j <= k; j++ ){
dp[v][j].insert(get(u, j, v));
}
dfs2(dfs2, v, u);
for ( int j = 0; j <= k; j++ ){
er(dp[v][j], get(u, j, v));
}
for ( int j = 0; j <= k; j++ ){
dp[u][j].insert(get(v, j, u));
}
}
};
dfs2(dfs2, 0, -1);
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
5 2
3 1 2 4 1
5 2
1 2
2 3
3 4
*/
# | 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... |