Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- typedef long long ll;
- const int maxn = 5e4 + 10;
- const int maxk = 155;
- const ll INF = 1e18;
- int n, k;
- vector<int> graph[maxn];
- ll v[maxn];
- vector<int> top_sort;
- int subtree_size[maxn];
- ll dp[maxn][maxk];
- void dfs(int node, int parent) {
- subtree_size[node] = 1;
- for(int neighbour : graph[node]) {
- if(neighbour != parent) {
- dfs(neighbour, node);
- subtree_size[node] += subtree_size[neighbour];
- }
- }
- top_sort.push_back(node);
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin >> n >> k;
- for(int i = 0; i < n; i++) {
- cin >> v[i];
- }
- for(int i = 1; i < n; i++) {
- int a, b;
- cin >> a >> b;
- a--; b--;
- graph[a].push_back(b);
- graph[b].push_back(a);
- }
- dfs(0, -1);
- reverse(top_sort.begin(), top_sort.end());
- for(int i = 0; i < maxn; i++) {
- for(int j = 0; j < maxk; j++) {
- dp[i][j] = -INF;
- }
- }
- dp[0][k] = 0;
- for(int i = 0; i < n; i++) {
- int node = top_sort[i];
- for(int j = 0; j <= k; j++) {
- if(dp[i][j] == -INF) continue;
- dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + v[node]);
- if(j >= 1) {
- dp[i + subtree_size[node]][j - 1] = max(dp[i + subtree_size[node]][j - 1], dp[i][j]);
- }
- }
- }
- ll res = -INF;
- for(int j = 0; j <= k; j++) {
- res = max(res, dp[n][j]);
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement