fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5. typedef pair<int, int> ii;
  6.  
  7. const int INF = 1e9;
  8. const ll LINF = 1e18;
  9.  
  10. const int N = 2e5 + 5;
  11.  
  12. int n, q;
  13. int t[N];
  14.  
  15. int nxt[30][N]; // nxt[k][u]: là đỉnh mà ta đến được nếu xuất phát từ đỉnh u và đi qua 2^k cổng dịch chuyển
  16.  
  17. void precompute() {
  18. for (int u = 1; u <= n; u++) nxt[0][u] = t[u];
  19.  
  20. for (int k = 1; k <= 29; k++) {
  21. for (int u = 1; u <= n; u++) {
  22. nxt[k][u] = nxt[k - 1][nxt[k - 1][u]];
  23. }
  24. }
  25. }
  26.  
  27. // đỉnh mà ta đến được nếu xuất phát từ đỉnh u và đi qua i cổng dịch chuyển
  28. int jump(int u, int i) {
  29. for (int k = 0; k <= 29; k++) {
  30. if (i & (1 << k)) {
  31. u = nxt[k][u];
  32. }
  33. }
  34. return u;
  35. }
  36.  
  37. int main() {
  38. ios::sync_with_stdio(0); cin.tie(0);
  39. cin >> n >> q;
  40. for (int i = 1; i <= n; i++) cin >> t[i];
  41.  
  42. precompute();
  43.  
  44. while (q--) {
  45. int u, i;
  46. cin >> u >> i;
  47. int ans = jump(u, i);
  48. cout << ans << '\n';
  49. }
  50. }
Success #stdin #stdout 0.01s 23960KB
stdin
4 3
2 1 1 4
1 2
3 4
4 1
stdout
1
2
4