YEZAELP

PROG-1091: เรียงบนต้นไม้ (treeinc)

Jun 19th, 2020
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int INF=1e9;
  4. using pii=pair<int,int>;
  5. int n;
  6. vector <int> g[300001];
  7.  
  8. int main(){
  9.  
  10.     scanf("%d",&n);
  11.     vector <int> dis(n+1,-INF);
  12.  
  13.     for(int i=1;i<n;i++){
  14.         int u,v;
  15.         scanf("%d %d",&u,&v);
  16.         g[u].push_back(v);
  17.         g[v].push_back(u);
  18.         sort(g[u].begin(),g[u].end(),greater<int>());
  19.         sort(g[v].begin(),g[v].end(),greater<int>());
  20.     }
  21.  
  22.     int max_node=0;
  23.     for(int i=1;i<=n;i++){
  24.         if(dis[i]!=-INF)
  25.             continue;
  26.         queue <pii> q;
  27.         q.push({1,i});
  28.         dis[i]=1;
  29.         while(q.size()>0){
  30.             int u,d;
  31.             d=q.front().first;
  32.             u=q.front().second;
  33.             q.pop();
  34.             max_node = max(max_node,d);
  35.             for(auto v:g[u]){
  36.                 if(v>u && dis[u]+1>dis[v]) {
  37.                     dis[v]=dis[u]+1;
  38.                     q.push({d+1,v});
  39.                 }
  40.                 else
  41.                     break;
  42.             }
  43.         }
  44.     }
  45.     printf("%d",max_node);
  46.  
  47.     return 0;
  48. }
Add Comment
Please, Sign In to add comment