Advertisement
Guest User

centroid

a guest
Jan 21st, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <stdio.h>
  3.  
  4. #define pb push_back
  5. #define pp pop_back
  6. #define sz(a) (int)(a.size())
  7. #define mp make_pair
  8. #define F first
  9. #define S second
  10. #define next nneexxtt
  11. #define left lleefftt
  12. #define right rriigghht
  13.  
  14. using namespace std;
  15.  
  16. typedef long long ll;
  17. typedef unsigned long long ull;
  18. typedef long double ld;
  19. typedef pair<int, int> pii;
  20.  
  21. const int N = (int)1e5 + 123;
  22. const ll INF = (ll)1e18 + 123;
  23. const int inf = (int)1e9 + 123;
  24.  
  25. int n, m, sub[100011];
  26. vector<int> g[100011];
  27. bool del[100011];
  28.  
  29. void dfs(int x, int par = -1) {
  30. sub[x] = 1;
  31. for(auto to : g[x]) {
  32. if(to == par || del[to]) continue;
  33. dfs(to, x);
  34. sub[x] += sub[to];
  35. }
  36. }
  37.  
  38. int get_centroid(int x) {
  39. bool ch;
  40. int now = x, Sz = sub[x], par = -1;
  41. while(1) {
  42. ch = 0;
  43. for(auto to : g[now]) {
  44. if(to == par || del[to]) continue;
  45. if(sub[to] * 2 >= Sz) {
  46. par = now, now = to, ch = 1;
  47. break;
  48. }
  49. }
  50. if(!ch) break;
  51. }
  52. return now;
  53. }
  54.  
  55. void show(int x, int par = -1) {
  56. cout << x << " ";
  57. for(auto to : g[x]) {
  58. if(to == par || del[to]) continue;
  59. show(to, x);
  60. }
  61. }
  62.  
  63. void calc(int x, int par = -1) {
  64. dfs(x);
  65. x = get_centroid(x);
  66. cout << "\n\nCentroid: " << x << " Tree:\n";
  67. show(x);
  68. del[x] = 1;
  69. for(auto to : g[x]) {
  70. if(del[to] || to == par) continue;
  71. calc(to, x);
  72. }
  73. }
  74.  
  75. int main() {
  76. cin >> n;
  77. for(int i = 1, a, b; i <= n - 1; i ++) {
  78. cin >> a >> b;
  79. g[a].pb(b);
  80. g[b].pb(a);
  81. }
  82. calc(1);
  83. return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement