Created
March 20, 2018 17:53
-
-
Save fredbr/cd60ecde5e54554540059ae4345ee202 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
#define ff first | |
#define ss second | |
using namespace std; | |
const int maxn = 500100; | |
typedef pair<int, int> ii; | |
vector<int> v[maxn]; | |
int dist1[maxn]; | |
int dist2[maxn]; | |
ii dfs1(int x, int p) | |
{ | |
ii ans = {0, x}; | |
for (int u : v[x]) { | |
if (u == p) continue; | |
ans = max(ans, dfs1(u, x)); | |
} | |
ans.ff++; | |
return ans; | |
} | |
void dfs2(int *dist, int x, int p) | |
{ | |
for (int u : v[x]) { | |
if (u == p) continue; | |
dist[u] = dist[x]+1; | |
dfs2(dist, u, x); | |
} | |
} | |
int main() | |
{ | |
ios_base::sync_with_stdio(false); | |
cin.tie(0); | |
int n; | |
cin >> n; | |
for (int i = 1; i < n; i++) { | |
int a, b; | |
cin >>a >> b; | |
v[a].push_back(b); | |
v[b].push_back(a); | |
} | |
ii d1 = dfs1(1, 1); | |
ii d2 = dfs1(d1.ss, d1.ss); | |
dfs2(dist1, d1.ss, d1.ss); | |
dfs2(dist2, d2.ss, d2.ss); | |
for (int i = 1; i <= n; i++) { | |
int ans = max(dist1[i], dist2[i]); | |
cout << ans+1 << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment