Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define int int64_t
- using namespace std;
- const int N = 2e5 + 1;
- int n, k;
- vector <int> v [N];
- vector <int> how_much, root_distance;
- bool visied [N] = {};
- void DFS(int u)
- {
- visied [u] = 1;
- if (v [u].empty())
- {
- how_much [u] = 0;
- return;
- }
- for (int i = 0; i < v [u].size(); i++)
- {
- if (!visied [v [u] [i]])
- {
- root_distance [v [u] [i]] = root_distance [u] + 1;
- DFS(v [u] [i]);
- how_much [u] += how_much [v [u] [i]] + 1;
- }
- }
- }
- int32_t main()
- {
- cin >> n >> k;
- how_much.resize(n + 1);
- root_distance.resize(n + 1);
- how_much = {};
- root_distance = {};
- for (int i = 1; i < n; i++)
- {
- int u, l;
- cin >> u >> l;
- v [u].push_back(l);
- v [l].push_back(u);
- }
- root_distance [1] = 0;
- DFS(1);
- int ans [n];
- ans [0] = LLONG_MIN;
- for (int i = 1; i <= n; i++)
- ans [i] = root_distance [i] - how_much [i];
- sort(ans, ans + n + 1, greater<int>());
- int sum = 0;
- for (int i = 0; i < k; i++)
- sum += ans [i];
- cout << sum;
- }
Advertisement
Add Comment
Please, Sign In to add comment