CF1337C (base tree dp)

Keywords: iOS

Linova and Kingdom

Thinking: it's easy to think that the deepest point may be the point we need. We choose the point from the deepest point. But in the best case, we choose a point to build a factory. This point has two son points. The two sons must also be factories. The value of the two son factories will be subtracted by 1 because the father node has built factories This is the difficulty. We just need to transfer the cost of two sons, maintain the value of two sons, and give the value to the father node, that is, the value of the father node minus the value lost by two sons. 2. In this way, we can maintain the value of each node, sort it, and select the first K.

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <cstdio>
 5 #include <vector>
 6 
 7 using namespace std;
 8 
 9 #define fi first
10 #define se second
11 #define ll long long
12 #define pb push_back 
13 
14 const int N = (int)2e5 + 10;
15 struct Tree{
16     int depth;
17     int son;
18     int value;
19     void cal(){
20         value = depth - son;
21     }
22     bool friend operator<(const Tree& a, const Tree& b){
23         return a.value > b.value;
24     }
25 }tree[N];
26 vector<int > G[N];
27 int n, k;
28 
29 void process(int now, int pre){
30     tree[now].son = 1;
31     tree[now].depth = tree[pre].depth + 1;
32     for(int to : G[now]){
33         if(to == pre) continue;
34         process(to, now);
35         tree[now].son += tree[to].son;
36     }
37     tree[now].cal();
38 }
39 
40 void solve(){
41     cin >> n >> k;
42     for(int i = 1; i < n; ++i){
43         int u, v;
44         cin >> u >> v;
45         G[u].pb(v);
46         G[v].pb(u);
47     }
48     process(1, 0);
49     sort(tree + 1, tree + 1 + n);
50     ll ans = 0;
51     for(int i = 1; i <= k; ++i){
52         ans += tree[i].value;
53     }
54     cout << ans << endl;
55 }
56 
57 int main(){
58 
59     ios::sync_with_stdio(false);
60     cin.tie(0);
61     cout.tie(0);
62     solve();
63 
64 
65     return 0;
66 }

Posted by djKale on Sat, 18 Apr 2020 07:59:19 -0700