Alex_tz307

CPH page 148

Sep 18th, 2020 (edited)
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int NMAX = 2e5 + 1;
  6.  
  7. vector < int > G[NMAX], d(NMAX), ans(NMAX);
  8.  
  9. void dfs1(int nod, int parent) {
  10.     for(int it : G[nod]) {
  11.         if(it == parent)
  12.             continue;
  13.         dfs1(it, nod);
  14.         d[nod] = max(d[nod], d[it] + 1);
  15.     }
  16. }
  17.  
  18. void dfs2(int nod, int parent, int parent_dist) {
  19.     ans[nod] = max(d[nod], parent_dist);
  20.     multiset < pair < int , int > > S;
  21.     S.insert(make_pair(parent_dist, 0));
  22.     for(int it : G[nod]) {
  23.         if(it == parent)
  24.             continue;
  25.         S.insert(make_pair(d[it] + 1, it));
  26.         if(S.size() == 3)
  27.             S.erase(S.begin());
  28.     }
  29.     for(int it : G[nod]) {
  30.         if(it == parent)
  31.             continue;
  32.         pair < int , int > p = *S.rbegin();
  33.         if(p.second != it)
  34.             dfs2(it, nod, p.first + 1);
  35.         else {
  36.             p = *(--S.rbegin());
  37.             dfs2(it, nod, p.first + 1);
  38.         }
  39.     }
  40. }
  41.  
  42. int main() {
  43.     ios_base::sync_with_stdio(false);
  44.     cin.tie(nullptr);
  45.     cout.tie(nullptr);
  46.     int N;
  47.     cin >> N;
  48.     for(int i = 1; i < N; ++i) {
  49.         int x, y;
  50.         cin >> x >> y;
  51.         G[x].emplace_back(y);
  52.         G[y].emplace_back(x);
  53.     }
  54.     dfs1(1, 0);
  55.     dfs2(1, 0, 0);
  56.     for(int i = 1; i <= N; ++i)
  57.         cout << ans[i] << ' ';
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment