Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int NMAX = 2e5 + 1;
- vector < int > G[NMAX], d(NMAX), ans(NMAX);
- void dfs1(int nod, int parent) {
- for(int it : G[nod]) {
- if(it == parent)
- continue;
- dfs1(it, nod);
- d[nod] = max(d[nod], d[it] + 1);
- }
- }
- void dfs2(int nod, int parent, int parent_dist) {
- ans[nod] = max(d[nod], parent_dist);
- multiset < pair < int , int > > S;
- S.insert(make_pair(parent_dist, 0));
- for(int it : G[nod]) {
- if(it == parent)
- continue;
- S.insert(make_pair(d[it] + 1, it));
- if(S.size() == 3)
- S.erase(S.begin());
- }
- for(int it : G[nod]) {
- if(it == parent)
- continue;
- pair < int , int > p = *S.rbegin();
- if(p.second != it)
- dfs2(it, nod, p.first + 1);
- else {
- p = *(--S.rbegin());
- dfs2(it, nod, p.first + 1);
- }
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int N;
- cin >> N;
- for(int i = 1; i < N; ++i) {
- int x, y;
- cin >> x >> y;
- G[x].emplace_back(y);
- G[y].emplace_back(x);
- }
- dfs1(1, 0);
- dfs2(1, 0, 0);
- for(int i = 1; i <= N; ++i)
- cout << ans[i] << ' ';
- }
Advertisement
Add Comment
Please, Sign In to add comment