ProgMe

Untitled

Apr 15th, 2020
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int int64_t
  3.  
  4. using namespace std;
  5. const int N = 2e5 + 1;
  6. int n, k;
  7. vector <int> v [N];
  8. vector <int> how_much, root_distance;
  9. bool visied [N] = {};
  10.  
  11. void DFS(int u)
  12. {
  13. visied [u] = 1;
  14. if (v [u].empty())
  15. {
  16. how_much [u] = 0;
  17. return;
  18. }
  19. for (int i = 0; i < v [u].size(); i++)
  20. {
  21. if (!visied [v [u] [i]])
  22. {
  23. root_distance [v [u] [i]] = root_distance [u] + 1;
  24. DFS(v [u] [i]);
  25. how_much [u] += how_much [v [u] [i]] + 1;
  26. }
  27. }
  28. }
  29.  
  30. int32_t main()
  31. {
  32. cin >> n >> k;
  33. how_much.resize(n + 1);
  34. root_distance.resize(n + 1);
  35. how_much = {};
  36. root_distance = {};
  37. for (int i = 1; i < n; i++)
  38. {
  39. int u, l;
  40. cin >> u >> l;
  41. v [u].push_back(l);
  42. v [l].push_back(u);
  43. }
  44. root_distance [1] = 0;
  45. DFS(1);
  46. int ans [n];
  47. ans [0] = LLONG_MIN;
  48. for (int i = 1; i <= n; i++)
  49. ans [i] = root_distance [i] - how_much [i];
  50. sort(ans, ans + n + 1, greater<int>());
  51. int sum = 0;
  52. for (int i = 0; i < k; i++)
  53. sum += ans [i];
  54. cout << sum;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment