Advertisement
bero_0401

to_leaf / max_length

Jun 26th, 2024 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | Source Code | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3. #define ll long long
  4.  
  5. int tt, tc;
  6. const int N = 100005;
  7. const ll INF = 1e18;
  8.  
  9. int to_leaf[N];
  10. int max_len[N];
  11. vector <int> adj[N];
  12. void dfs(int v , int par)
  13. {
  14.     int mx1 = -1; int mx2 = -1;
  15.     for(int u : adj[v])
  16.     {
  17.         if(u != par)
  18.         {
  19.             dfs(u , v);
  20.             to_leaf[v] = max(to_leaf[u] + 1  , to_leaf[v]);
  21.             if(mx1 <=  to_leaf[u]) {
  22.                 mx2 = mx1;
  23.                 mx1 = to_leaf[u];
  24.  
  25.             }
  26.             else if(mx2 < to_leaf[u])
  27.             {
  28.                 mx2 = to_leaf[u];
  29.             }
  30.  
  31.  
  32.         }
  33.     }
  34.     max_len[v] = mx1+mx2+2;
  35. }
  36.  
  37. void solve() {
  38.     int n , m; cin>>n>>m;
  39.  
  40.     for(int i =0 ; i<m; i++)
  41.     {
  42.         int u , v; cin>>u>>v;
  43.         adj[v].push_back(u);
  44.         adj[u].push_back(v);
  45.     }
  46.     dfs(1 , 0);
  47.     cout<<to_leaf[1]<<"\n";
  48.     cout<<to_leaf[2]<<"\n";
  49.     cout<<to_leaf[4]<<"\n";
  50.     cout<<max_len[1]<<"\n";
  51.  
  52.  
  53. }
  54.  
  55.  
  56.  
  57.  
  58.  
  59. int main() {
  60.     ios::sync_with_stdio(0); cin.tie(0);
  61.     tt = 1, tc = 1; cin >> tt;
  62.     while (tt--) solve(), tc++;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement