CSES - Shared codeLink to this code:
https://cses.fi/paste/409071e1689fa4cb6a3c5/
// cses - Tree Distances I
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long
#define INF (ll)1e18
ll i, i1, j, k, k1, t, n, m, res, check1, a, b, p[200010];
pair<ll, ll> m1[200010], m2[200010];
bool visited[200010];
vector<ll> adj[200010];
void dfs1(ll s) {
for (auto u : adj[s]) {
if (!visited[u]) {
visited[u] = true;
dfs1(u);
if (m1[u].first + 1 > m1[s].first) {
m2[s] = m1[s];
m1[s] = {m1[u].first + 1, u};
} else if (m1[u].first + 1 > m2[s].first) {
m2[s] = {m1[u].first + 1, u};
}
}
}
}
void dfs2(ll s) {
for (auto u : adj[s]) {
if (!visited[u]) {
visited[u] = true;
if (m1[s].second != u) {
p[u] = m1[s].first + 1;
} else {
p[u] = m2[s].first + 1;
}
p[u] = max(p[u], p[s] + 1);
dfs2(u);
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
// ifstream cin("input.txt");
// ofstream cout("output.txt");
cin >> n;
for (i = 0; i < n - 1; i++) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (i = 1; i <= n; i++) {
m1[i] = {0, -1}; m2[i] = {0, -1};
}
visited[1] = true;
dfs1(1);
p[1] = 0;
for (i = 2; i <= n; i++) {
visited[i] = false;
}
dfs2(1);
for (i = 1; i <= n; i++) {
cout << max(m1[i].first, p[i]) << ' ';
}
return 0;
}