- #include <iostream> 
- #include <vector> 
- #include <algorithm> 
-   
- using namespace std; 
-   
- const int MAXN = 200000; 
- vector<int> graph[MAXN + 1]; 
- int maxDist[MAXN + 1]; 
- int subtreeSize[MAXN + 1]; 
-   
- void dfs(int node, int parent, int depth) { 
-     maxDist[node] = depth; 
-     for (int neighbor : graph[node]) { 
-         if (neighbor != parent) { 
-             dfs(neighbor, node, depth + 1); 
-         } 
-     } 
- } 
-   
- void reroot(int node, int parent, int n) { 
-     // Store the maximum distance for the current node 
-     vector<int> distances; 
-     for (int neighbor : graph[node]) { 
-         if (neighbor != parent) { 
-             distances.push_back(maxDist[neighbor]); 
-         } 
-     } 
-   
-     // Sort distances to find the two largest 
-     sort(distances.rbegin(), distances.rend()); 
-   
-     for (int neighbor : graph[node]) { 
-         if (neighbor != parent) { 
-             // Calculate the maximum distance for the current neighbor 
-             int originalMax = maxDist[node]; 
-             int newMax = (distances.size() > 0 ? distances[0] : 0); 
-             if (distances[0] == maxDist[neighbor]) { 
-                 newMax = (distances.size() > 1 ? distances[1] : 0); 
-             } 
-             maxDist[neighbor] = max(maxDist[neighbor], originalMax + 1); 
-             reroot(neighbor, node, n); 
-             maxDist[neighbor] = originalMax; // Restore original maxDist 
-         } 
-     } 
- } 
-   
- int main() { 
-     int n; 
-     cin >> n; 
-   
-     for (int i = 0; i < n - 1; ++i) { 
-         int a, b; 
-         cin >> a >> b; 
-         graph[a].push_back(b); 
-         graph[b].push_back(a); 
-     } 
-   
-     // First DFS to find the farthest node from node 1 
-     dfs(1, -1, 0); 
-   
-     // Find the farthest node from node 1 
-     int farthestNode = 1; 
-     for (int i = 1; i <= n; ++i) { 
-         if (maxDist[i] > maxDist[farthestNode]) { 
-             farthestNode = i; 
-         } 
-     } 
-   
-     // Second DFS from the farthest node found 
-     fill(maxDist, maxDist + n + 1, 0); 
-     dfs(farthestNode, -1, 0); 
-   
-     // Rerooting to calculate maximum distances for all nodes 
-     reroot(farthestNode, -1, n); 
-   
-     // Output the maximum distances 
-     for (int i = 1; i <= n; ++i) { 
-         cout << maxDist[i] << " "; 
-     } 
-     cout << endl; 
-   
-     return 0; 
- }