Advertisement
bero_0401

all longest path

Jun 26th, 2024 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | Source Code | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3. #define ll long long
  4.  
  5.  
  6. int tt, tc;
  7. const int N = 100005;
  8. const ll INF = 1e18;
  9.  
  10.  
  11.  
  12. #define maxN 200005
  13.  
  14. // Adjacency List to store the graph
  15. vector<int> adj[maxN];
  16.  
  17. int height[maxN];
  18.  
  19. int dist[maxN];
  20.  
  21.  
  22. void dfs1(int cur, int par)
  23. {
  24.  
  25.     for (auto u : adj[cur]) {
  26.  
  27.         if (u != par) {
  28.  
  29.             dfs1(u, cur);
  30.             height[cur] = max(height[cur], height[u] + 1);
  31.         }
  32.     }
  33.  
  34. }
  35.  
  36. void dfs2(int cur, int par)
  37. {
  38.     int max1 = -1;
  39.     int max2 = -1;
  40.  
  41.     for (auto u : adj[cur]) {
  42.  
  43.         if (u != par) {
  44.  
  45.             if (height[u] >= max1) {
  46.                 max2 = max1;
  47.                 max1 = height[u];
  48.             }
  49.             else if (height[u] > max2) {
  50.                 max2 = height[u];
  51.             }
  52.         }
  53.     }
  54.  
  55.  
  56.     for (auto u : adj[cur]) {
  57.         if (u != par) {
  58.  
  59.             if (max1 == height[u])
  60.                 dist[u] = 1 + max(1 + max2, dist[cur]);
  61.             else
  62.                 dist[u] = 1 + max(1 + max1, dist[cur]);
  63.  
  64.             dfs2(u, cur);
  65.         }
  66.     }
  67. }
  68.  
  69.  
  70. void solve() {
  71.     int n ; cin>>n;
  72.  
  73.     for(int i =0 ; i<n - 1; i++)
  74.     {
  75.         int u , v; cin>>u>>v;
  76.         adj[v].push_back(u);
  77.         adj[u].push_back(v);
  78.     }
  79.     dfs1(1 , 0);
  80.     dfs2(1 , 0);
  81.     for (int i = 1; i <= n; i++)
  82.         cout << max(dist[i], height[i]) << " ";
  83.  
  84. }
  85.  
  86.  
  87.  
  88.  
  89.  
  90. int main() {
  91.     ios::sync_with_stdio(0); cin.tie(0);
  92.     tt = 1, tc = 1; //cin >> tt;
  93.     while (tt--) solve(), tc++;
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement