Advertisement
Guest User

kth number on path

a guest
Apr 12th, 2021
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define x first
  3. #define y second
  4. #define pii pair<int,int>
  5. using ll=long long;
  6. #define pb push_back
  7. #define eb emplace_back
  8. #define vi vector<int>
  9. #define vl vector<ll>
  10. #define all(a) begin(a),end(a)
  11.  
  12. using namespace std;
  13.  
  14. const int N=100010,M=1<<17;
  15. int q,n,de[N],par[20][N],nod[N],cn[N],req[N],seg[M*2+10];
  16. ll h[N];
  17. vi ch[N];
  18. vector<pii> ord,qu[N];
  19.  
  20. void dfs(int i,int p=0)
  21. {
  22.     par[0][i]=p;
  23.     ord.pb({i,1});
  24.     for (auto a: ch[i]) if (a!=p) de[a]=de[i]+1,dfs(a,i);
  25.     ord.pb({i,-1});
  26. }
  27.  
  28. int lca(int a,int b)
  29. {
  30.     for (int j=17;j>=0;--j) if (de[a]-de[b]>=(1<<j)) a=par[j][a];
  31.     for (int j=17;j>=0;--j) if (de[b]-de[a]>=(1<<j)) b=par[j][b];
  32.     if (a==b) return a;
  33.     for (int j=17;j>=0;--j) if (par[j][a]!=par[j][b]) a=par[j][a],b=par[j][b];
  34.     return par[0][a];
  35. }
  36.  
  37. int main()
  38. {
  39.     ios_base::sync_with_stdio(0);
  40.     cin.tie(0);
  41.     cin>>n>>q;
  42.     vl v;
  43.     for (int i=0;i<n;++i) cin>>h[i],v.pb(h[i]);
  44.     sort(all(v));
  45.     v.erase(unique(all(v)),v.end());
  46.     for (int i=0;i<n;++i) h[i]=lower_bound(all(v),h[i])-v.begin();
  47.     for (int i=1;i<n;++i)
  48.     {
  49.         int a,b;
  50.         cin>>a>>b;
  51.         --a;
  52.         --b;
  53.         ch[a].pb(b);
  54.         ch[b].pb(a);
  55.     }
  56.     dfs(0);
  57.     for (int j=1;j<18;++j) for (int i=0;i<n;++i) par[j][i]=par[j-1][par[j-1][i]];
  58.     for (int i=0;i<q;++i)
  59.     {
  60.         int a,b;
  61.         cin>>a>>b>>req[i];
  62.         --a;
  63.         --b;
  64.         qu[a].pb({i,1});
  65.         qu[b].pb({i,1});
  66.         int z=lca(a,b);
  67.         qu[z].pb({i,-1});
  68.         if (z) qu[par[0][z]].pb({i,-1});
  69.         nod[i]=1;
  70.     }
  71.     for (int z=16;z>=0;--z)
  72.     {
  73.         for (int i=0;i<q;++i) nod[i]*=2;
  74.         memset(cn,0,sizeof(cn));
  75.         for (auto x: ord)
  76.         {
  77.             seg[(h[x.x]+M)>>z]+=x.y;
  78.             if (x.y==1) for (auto a: qu[x.x])
  79.             {
  80.                 cn[a.x]+=a.y*seg[nod[a.x]];
  81.             }
  82.         }
  83.         for (int i=0;i<q;++i)
  84.         {
  85.             if (cn[i]<req[i])
  86.             {
  87.                 req[i]-=cn[i];
  88.                 ++nod[i];
  89.             }
  90.         }
  91.     }
  92.     for (int i=0;i<q;++i) cout<<v[nod[i]-M]<<'\n';
  93. }
  94.  
  95.  
  96.  
  97.  
  98.  
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement