-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA.cpp
More file actions
66 lines (52 loc) · 1.34 KB
/
A.cpp
File metadata and controls
66 lines (52 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "bits/stdc++.h"
using namespace std;
#define int long long
const int N = 5e5;
int n, k;
vector<int> adj[N];
int happiness[N], industry[N], dep[N];
int vis[N];
int cnt[N];
void dfs(int root, int cur_score) { //to calculate the happiness of each node.
if (vis[root])return;
vis[root] = 1;
happiness[root] = cur_score;
for (auto i: adj[root]) {
dfs(i, cur_score + (industry[root] == 0 ? 1 : 0));
}
}
void dfs2(int root, int d) {//calculate
if (vis[root])return;
vis[root] = 1;
cnt[root] = 1;
dep[root] = d;
for (auto i: adj[root]) {
if (!vis[i]) {
dfs2(i, d + 1);
cnt[root] += cnt[i];
}
}
}
signed main() {
scanf("%lld%lld", &n, &k);
for (int i = 1; i < n; i++) {
int u, v;
scanf("%lld%lld", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs2(1, 0);
fill(vis, vis + N, 0);
vector<pair<int, int>> v;
for (int i = 1; i <= n; i++)
v.emplace_back(dep[i] - cnt[i], i);
sort(v.rbegin(), v.rend());
for (int i = 0; i < k; i++)
industry[v[i].second] = 1;
dfs(1, 0);
int ans = 0;
for (int i = 1; i <= n; i++)
if (industry[i] == 1)
ans += happiness[i];
printf("%lld", ans);
}