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. const int LOG = 30;
  12.  
  13. int n, q;
  14. int t[N];
  15.  
  16. int nxt[LOG][N]; // nxt[i][u]: Đỉnh mà ta đến được nếu xuất phát từ đỉnh u và đi qua 2^i cổng dịch chuyển
  17.  
  18. void precompute() {
  19. for (int u = 1; u <= n; u++) nxt[0][u] = t[u];
  20.  
  21. for (int i = 1; i < LOG; i++) {
  22. for (int u = 1; u <= n; u++) {
  23. nxt[i][u] = nxt[i - 1][nxt[i - 1][u]];
  24. }
  25. }
  26. }
  27.  
  28. // Đỉnh mà ta đến được nếu xuất phát từ đỉnh u và đi qua k cổng dịch chuyển
  29. int jump(int u, int k) {
  30. for (int i = 0; i < LOG; i++) {
  31. if ((k >> i) & 1) u = nxt[i][u];
  32. }
  33. return u;
  34. }
  35.  
  36. int main() {
  37. ios::sync_with_stdio(0); cin.tie(0);
  38. cin >> n >> q;
  39. for (int i = 1; i <= n; i++) cin >> t[i];
  40.  
  41. precompute();
  42.  
  43. while (q--) {
  44. int u, k;
  45. cin >> u >> k;
  46. int ans = jump(u, k);
  47. cout << ans << '\n';
  48. }
  49. }
Success #stdin #stdout 0.01s 26032KB
stdin
4 3
2 1 1 4
1 2
3 4
4 1
stdout
1
2
4