Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- #define ll long long
- int tt, tc;
- const int N = 100005;
- const ll INF = 1e18;
- #define maxN 200005
- // Adjacency List to store the graph
- vector<int> adj[maxN];
- int height[maxN];
- int dist[maxN];
- void dfs1(int cur, int par)
- {
- for (auto u : adj[cur]) {
- if (u != par) {
- dfs1(u, cur);
- height[cur] = max(height[cur], height[u] + 1);
- }
- }
- }
- void dfs2(int cur, int par)
- {
- int max1 = -1;
- int max2 = -1;
- for (auto u : adj[cur]) {
- if (u != par) {
- if (height[u] >= max1) {
- max2 = max1;
- max1 = height[u];
- }
- else if (height[u] > max2) {
- max2 = height[u];
- }
- }
- }
- for (auto u : adj[cur]) {
- if (u != par) {
- if (max1 == height[u])
- dist[u] = 1 + max(1 + max2, dist[cur]);
- else
- dist[u] = 1 + max(1 + max1, dist[cur]);
- dfs2(u, cur);
- }
- }
- }
- void solve() {
- int n ; cin>>n;
- for(int i =0 ; i<n - 1; i++)
- {
- int u , v; cin>>u>>v;
- adj[v].push_back(u);
- adj[u].push_back(v);
- }
- dfs1(1 , 0);
- dfs2(1 , 0);
- for (int i = 1; i <= n; i++)
- cout << max(dist[i], height[i]) << " ";
- }
- int main() {
- ios::sync_with_stdio(0); cin.tie(0);
- tt = 1, tc = 1; //cin >> tt;
- while (tt--) solve(), tc++;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement