Advertisement
mickypinata

IPST60: Deep

Nov 20th, 2021
703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 2e5 + 5;
  5. const int M = 300 + 5;
  6. const int logN = log2(2e5);
  7.  
  8. vector<int> branch, adj[M];
  9. int chd[N][logN + 1];
  10. bool hasBranch[N];
  11.  
  12. int s, a, b;
  13. int rndDir(){
  14.     int res = (s & 8) >> 3;
  15.     s = (s * a + b) % 40507;
  16.     return res;
  17. }
  18.  
  19. void dive(int &u, int &rnk){
  20.     if(hasBranch[u]){
  21.         return;
  22.     }
  23.     int depth = 0;
  24.     int v = u;
  25.     for(int e = logN; e >= 0; --e){
  26.         if(!hasBranch[chd[v][e]]){
  27.             v = chd[v][e];
  28.             depth += 1 << e;
  29.         }
  30.     }
  31.     depth += 1;
  32.     if(depth <= rnk){
  33.         rnk -= depth;
  34.         u = chd[v][0];
  35.         return;
  36.     }
  37.     for(int e = logN; e >= 0; --e){
  38.         if((1 << e) <= rnk){
  39.             u = chd[u][e];
  40.             rnk -= 1 << e;
  41.         }
  42.     }
  43. }
  44.  
  45. int main(){
  46.  
  47.     int nVertex, Q;
  48.     scanf("%d%d", &nVertex, &Q);
  49.     int nBranch = 0;
  50.     for(int u = 1; u <= nVertex; ++u){
  51.         int v1, v2;
  52.         scanf("%d%d", &v1, &v2);
  53.         if(v1 == -1 && v2 == -1){
  54.             hasBranch[u] = false;
  55.             chd[u][0] = u;
  56.         } else if(v1 == -1){
  57.             hasBranch[u] = false;
  58.             chd[u][0] = ++v2;
  59.         } else if(v2 == -1){
  60.             hasBranch[u] = false;
  61.             chd[u][0] = ++v1;
  62.         } else {
  63.             hasBranch[u] = true;
  64.             chd[u][0] = u;
  65.             branch.push_back(u);
  66.             adj[nBranch].push_back(++v1);
  67.             adj[nBranch].push_back(++v2);
  68.             ++nBranch;
  69.         }
  70.     }
  71.     for(int e = 1; e <= logN; ++e){
  72.         for(int u = 1; u <= nVertex; ++u){
  73.             chd[u][e] = chd[chd[u][e - 1]][e - 1];
  74.         }
  75.     }
  76.     while(Q--){
  77.         int rnk;
  78.         scanf("%d%d%d%d", &rnk, &s, &a, &b);
  79.         int u = 1;
  80.         while(rnk > 0){
  81.             dive(u, rnk);
  82.             if(rnk > 0 && hasBranch[u]){
  83.                 int i = lower_bound(branch.begin(), branch.end(), u) - branch.begin();
  84.                 u = adj[i][rndDir()];
  85.                 --rnk;
  86.             }
  87.         }
  88.         cout << u - 1 << '\n';
  89.     }
  90.  
  91.     return 0;
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement