fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4. #define sz(st) int(st.size())
  5. #define all(st) st.begin(), st.end()
  6.  
  7.  
  8. void Solve()
  9. {
  10. int n;
  11. cin >> n;
  12. vector<int> v(n + 1);
  13. for (int i = 1; i <= n; i++) {
  14. cin >> v[i];
  15. }
  16. vector < vector < int >>nxt(20, vector<int>(n + 1, n + 1));
  17.  
  18. for (int i = 1;i <= n;i++) nxt[0][i] = v[i];
  19.  
  20. for (int i = 1;i < 20;i++) {
  21. for (int j = 1;j <= n;j++) {
  22. nxt[i][j] = nxt[i - 1][nxt[i - 1][j]];
  23. }
  24. }
  25. auto jump = [&](int i, int x) {
  26. for (int j = 0; j < 20; j++) {
  27. if (x & (1 << j)) {
  28. i = nxt[j][i];
  29. }
  30. }
  31. return i;
  32. };
  33.  
  34. auto apply_k_times = [&](int k) {
  35. vector < int > ret(n + 1);
  36. for (int i = 1;i <= n;i++)
  37. ret[jump(i, k - 1)] = 1;
  38. return ret;
  39. };
  40.  
  41.  
  42. ll l = 2, r = n * 4, ans = n * 4;
  43. while (l <= r) {
  44. ll mid = (l + r) / 2;
  45.  
  46. auto x = apply_k_times(mid);
  47. auto x_1 = apply_k_times(mid - 1);
  48.  
  49. if (x == x_1) {
  50. ans = mid;
  51. r = mid - 1;
  52. }
  53. else {
  54. l = mid + 1;
  55. }
  56. }
  57. cout << ans;
  58.  
  59.  
  60. }
  61.  
  62. signed main()
  63. {
  64. #if LOCAL
  65. freopen("input.txt", "r", stdin);
  66. freopen("output.txt", "w", stdout);
  67. #endif
  68. ios_base::sync_with_stdio(false);
  69. cin.tie(nullptr);
  70. int t = 1;
  71. cin >> t;
  72. for (int tc = 1; tc <= t; tc++) {
  73. Solve();
  74. cout << "\n";
  75. }
  76. return 0;
  77. }
Success #stdin #stdout 0s 5288KB
stdin
5
2
2 1
5
2 3 4 5 1
5
2 1 4 2 3
5
4 1 1 5 4
10
4 3 9 1 6 7 9 10 10 3
stdout
2
2
5
4
5