Guest User

a.cpp

a guest
Mar 7th, 2026
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define f first
  3. #define s second
  4. #define ll long long
  5. #define IOS ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
  6.  
  7. using namespace std;
  8. const int MAXN = 1e6 + 10;
  9. const int MOD = 1e9 + 7;
  10.  
  11. int calc_cnt_vertex(int x, int pr = -1){
  12.     int cnt_vertex = 1;
  13.     for (int to : g[x]){
  14.         if (to != pr && !removed[to]){
  15.            cnt[to] = calc_cnt_vertex(to, x);
  16.            cnt_vertex += cnt[to];
  17.         }
  18.     }
  19.     return cnt_vertex;
  20. }
  21.  
  22. int find_centroid(int x, int n, int pr = -1){
  23.  
  24.     for (int to : g[x]){
  25.         if (to != pr && !removed[to]){
  26.             if (cnt[to] * 2 > n)
  27.                 return find_centroid(to, n, x);
  28.         }
  29.     }
  30.     return x;
  31. }
  32. void find_dist(int x, int h, int pr = -1){
  33.     dist[x] = h;
  34.     answer += all_dists[d - h];
  35.     for (int to : g[x]){
  36.         if (to != pr && !removed[to]){
  37.            find_dist(to, h + 1, x);
  38.         }
  39.     }
  40. }
  41.  
  42. void add_dist(int x, int pr = -1){
  43.     all_dists[dist[x]]++;
  44.     for (int to : g[x]){
  45.         if (to != pr && !removed[to]){
  46.            add_dist(to, x);
  47.         }
  48.     }
  49. }
  50.  
  51. void calc_ans(int x){
  52.     for (int i = 0; i <= cnt[x]; i++){
  53.         all_dist[i] = 0;
  54.     }
  55.     for (int to : g[x]){
  56.         if (!removed[to]){
  57.             find_dist(to, 1);
  58.             add_dist(to);
  59.         }
  60.     }
  61. }
  62.  
  63. void calc(int x, int lvl_centroid){
  64.     cnt[x] = calc_cnt_vertex(x);
  65.     int v = find_centroid(x, cnt[x]);
  66.  
  67.     removed[v] = true;
  68.     calc_ans(v);
  69.  
  70.     for (int to : g[v]){
  71.         if (!removed[to]){
  72.             calc(to, lvl_centroid + 1);
  73.         }
  74.     }
  75. }
  76.  
  77. int main(){
  78.     IOS;
  79.     int n;
  80.     cin >> n;
  81.     for (int i = 0; i < n - 1; i++){
  82.         int x, y;
  83.         cin >> x >> y;
  84.         g[x].pb(y);
  85.         g[y].pb(x);
  86.     }
  87.  
  88.     calc(1, 1);
  89.  
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment