prithivMLmods/Coder-Stat huggingface dataset:
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
// #include<bits/stdc++.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <set>
#include <vector>

/*
#include <boost/multiprecision/cpp_dec_float.hpp>
#include<boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
namespace mp = boost::multiprecision;
using Real = mp::number<mp::cpp_dec_float<1024>>;
using Bint = mp::cpp_int;
*/

using namespace std;

#define int long long
#define REP(i, s, e) for ((i) = (s); (i) < (e); (i)++)
#define RREP(i, s, e) for ((i) = ((s)-1); (i) >= (e); (i)--)
#define FOR(i, n) for ((i) = (0); (i) < (n); (i)++)
#define RFOR(i, n) for ((i) = ((n)-1); (i) >= (0); (i)--)
#define MOD 1000000007

signed main() {
  int N, K;
  int A[20000] = {0};
  int An[20000] = {0};
  cin >> N >> K;
  for (int i = 1; i <= N; i++) {
    cin >> A[i];
  }

  int i = 1;
  int n = 1;
  K--;
  while (K >= 0) {
    if (An[n] != 0) {
      int diff = i - An[n];
      K %= diff;
    }
    An[n] = i;
    i++;
    K--;
    n = A[n];
  }

  cout << n << endl;
}


Fixed submission:
// #include<bits/stdc++.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <set>
#include <vector>

/*
#include <boost/multiprecision/cpp_dec_float.hpp>
#include<boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
namespace mp = boost::multiprecision;
using Real = mp::number<mp::cpp_dec_float<1024>>;
using Bint = mp::cpp_int;
*/

using namespace std;

#define int long long
#define REP(i, s, e) for ((i) = (s); (i) < (e); (i)++)
#define RREP(i, s, e) for ((i) = ((s)-1); (i) >= (e); (i)--)
#define FOR(i, n) for ((i) = (0); (i) < (n); (i)++)
#define RFOR(i, n) for ((i) = ((n)-1); (i) >= (0); (i)--)
#define MOD 1000000007

signed main() {
  int N, K;
  int A[200010] = {0};
  int An[200010] = {0};
  cin >> N >> K;
  for (int i = 1; i <= N; i++) {
    cin >> A[i];
  }

  int i = 1;
  int n = 1;
  K--;
  while (K >= 0) {
    if (An[n] != 0) {
      int diff = i - An[n];
      K %= diff;
    }
    An[n] = i;
    i++;
    K--;
    n = A[n];
  }

  cout << n << endl;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int N;
ll K;
vector<bool> visited;
vector<int> dic;
vector<int> A;

int dfs(int cur) {
  K--;
  if (visited[cur])
    return cur;
  if (K == 0)
    return cur;
  visited[cur] = true;
  dic.push_back(cur);
  dfs(A[cur]);
}

int main() {
  cin >> N >> K;
  A.resize(N);
  visited.resize(N);
  fill(visited.begin(), visited.end(), false);

  for (int i = 0; i < N; i++) {
    cin >> A[i];
    A[i]--;
  }

  visited[0] = true;
  dic.push_back(0);

  int cur = dfs(A[0]);
  ll idx = 0;
  vector<int> last;

  int i;
  for (i = 0; i < (int)dic.size(); i++) {
    if (dic[i] == cur) {
      idx = i;
      last.push_back(dic[i]);
      break;
    }
  }

  for (int j = i + 1; j < (int)dic.size(); j++) {
    last.push_back(dic[j]);
  }

  idx = (ll)dic.size() - idx;

  if (K == 0)
    cout << (cur + 1) << endl;
  else
    cout << (last[K % idx] + 1) << endl;

  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int N;
ll K;
vector<bool> visited;
vector<int> dic;
vector<int> A;

int dfs(int cur) {
  K--;
  if (visited[cur])
    return cur;
  if (K == 0)
    return cur;
  visited[cur] = true;
  dic.push_back(cur);
  return dfs(A[cur]);
}

int main() {
  cin >> N >> K;
  A.resize(N);
  visited.resize(N);
  fill(visited.begin(), visited.end(), false);

  for (int i = 0; i < N; i++) {
    cin >> A[i];
    A[i]--;
  }

  visited[0] = true;
  dic.push_back(0);

  int cur = dfs(A[0]);
  ll idx = 0;
  vector<int> last;

  int i;
  for (i = 0; i < (int)dic.size(); i++) {
    if (dic[i] == cur) {
      idx = i;
      last.push_back(dic[i]);
      break;
    }
  }

  for (int j = i + 1; j < (int)dic.size(); j++) {
    last.push_back(dic[j]);
  }

  idx = (ll)dic.size() - idx;

  if (K == 0)
    cout << (cur + 1) << endl;
  else
    cout << (last[K % idx] + 1) << endl;

  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;

const int nm = 1e5;
int n, a, b[nm], s[nm], t, c, r;
string k;

int main() {
  cin >> n >> k;
  a = 0;
  for (int i = 0; i < n; i++) {
    cin >> b[i];
    b[i]--;
  }
  if (k.size() <= 6) {
    int kInt = stoi(k);
    for (int i = 0; i < kInt; i++)
      a = b[a];
    cout << a + 1 << endl;
    return 0;
  }
  fill(s, s + n, -1);
  c = a;
  for (int i = 0;; i++, c = b[c])
    if (s[c] < 0)
      s[c] = i;
    else {
      r = -s[c];
      t = i - s[c];
      break;
    }
  for (int i = 0, b = 1; i < (int)k.size(); i++, b = b * 10 % t)
    r += (k[k.size() - 1 - i] - '0') * b;
  r %= t;
  if (r < 0)
    r += t;
  for (int i = 0; i < r; i++)
    c = b[c];
  cout << c + 1 << endl;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;

const int nm = 3e5;
int n, a, b[nm], s[nm], t, c, r;
string k;

int main() {
  cin >> n >> k;
  a = 0;
  for (int i = 0; i < n; i++) {
    cin >> b[i];
    b[i]--;
  }
  if (k.size() <= 6) {
    int kInt = stoi(k);
    for (int i = 0; i < kInt; i++)
      a = b[a];
    cout << a + 1 << endl;
    return 0;
  }
  fill(s, s + n, -1);
  c = a;
  for (int i = 0;; i++, c = b[c])
    if (s[c] < 0)
      s[c] = i;
    else {
      r = -s[c];
      t = i - s[c];
      break;
    }
  for (int i = 0, b = 1; i < (int)k.size(); i++, b = b * 10 % t)
    r += (k[k.size() - 1 - i] - '0') * b;
  r %= t;
  if (r < 0)
    r += t;
  for (int i = 0; i < r; i++)
    c = b[c];
  cout << c + 1 << endl;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

void solve() {
  ll n, k;
  cin >> n >> k;
  vector<int> v(n + 5), vis(n + 5, -1);
  for (int i = 1; i <= n; i++)
    cin >> v[i];
  int i, ans = 1, cl = 0;
  vis[1] = 0;
  for (i = 1; i <= k; i++) {
    ans = v[ans];
    if (vis[ans] != -1) {
      cl = i - vis[ans];
      break;
    } else {
      vis[ans] = i;
    }
  }
  // cout << ans << " " << i << " " << cl << '\n';
  // starting at ans move k - i
  k = (k - i) % cl;
  while (k--)
    ans = v[ans];
  cout << ans << '\n';
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

  solve();
  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

void solve() {
  ll n, k;
  cin >> n >> k;
  vector<int> v(n + 5), vis(n + 5, -1);
  for (int i = 1; i <= n; i++)
    cin >> v[i];
  int i, ans = 1, cl = 0;
  vis[1] = 0;
  for (i = 1; i <= k; i++) {
    ans = v[ans];
    if (vis[ans] != -1) {
      cl = i - vis[ans];
      break;
    } else {
      vis[ans] = i;
    }
  }
  // cout << ans << " " << i << " " << cl << '\n';
  // starting at ans move k - i
  if (cl) {
    k = (k - i) % cl;
    while (k--)
      ans = v[ans];
  }
  cout << ans << '\n';
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

  solve();
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

const int D = 110;
const int N = 2000000;
int to[D][N];
int main() {
  int n;
  ll k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++) {
    cin >> to[0][i];
  }
  rep(i, D) {
    for (int j = 1; j <= n; j++) {
      to[i + 1][j] = to[i][to[i][j]];
    }
  }
  int now_town = 1;
  int tmp = -1;
  do {
    tmp++;
    if (k % 2 == 1) {
      now_town = to[tmp][now_town];
    }
    k /= 2;
  } while (k != 0);
  cout << now_town << endl;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

const int D = 110;
const int N = 2000000;
int to[D][N];
int main() {
  int n;
  ll k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++) {
    cin >> to[0][i];
  }
  rep(i, D - 1) {
    for (int j = 1; j <= n; j++) {
      to[i + 1][j] = to[i][to[i][j]];
    }
  }
  int now_town = 1;
  int tmp = -1;
  do {
    tmp++;
    if (k % 2 == 1) {
      now_town = to[tmp][now_town];
    }
    k /= 2;
  } while (k != 0);
  cout << now_town << endl;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define MOD 1000000007
#define MOD2 998244353
#define INF ((1 << 30) - 1)
#define LINF (1LL << 60)
#define EPS (1e-10)
typedef long long Int;
typedef pair<Int, Int> P;

int to[110000];
bool reached[110000];
int cnt[110000];

int main() {
  int n;
  Int k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++) {
    cin >> to[i];
  }
  int now = 1;
  reached[1] = true;
  Int sumcnt = 0;
  int period = INF;
  while (true) {
    int nex = to[now];
    sumcnt++;
    if (sumcnt == k) {
      cout << nex << endl;
      return 0;
    }
    if (!reached[nex]) {
      reached[nex] = true;
      cnt[nex] = sumcnt;
    } else {
      period = sumcnt - cnt[nex];
      now = nex;
      break;
    }
    now = nex;
  }
  k -= sumcnt;
  k %= period;
  rep(i, k) {
    int nex = to[now];
    now = nex;
  }
  cout << now << endl;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define MOD 1000000007
#define MOD2 998244353
#define INF ((1 << 30) - 1)
#define LINF (1LL << 60)
#define EPS (1e-10)
typedef long long Int;
typedef pair<Int, Int> P;

int to[220000];
bool reached[220000];
int cnt[220000];

int main() {
  int n;
  Int k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++) {
    cin >> to[i];
  }
  int now = 1;
  reached[1] = true;
  Int sumcnt = 0;
  int period = INF;
  while (true) {
    int nex = to[now];
    sumcnt++;
    if (sumcnt == k) {
      cout << nex << endl;
      return 0;
    }
    if (!reached[nex]) {
      reached[nex] = true;
      cnt[nex] = sumcnt;
    } else {
      period = sumcnt - cnt[nex];
      now = nex;
      break;
    }
    now = nex;
  }
  k -= sumcnt;
  k %= period;
  rep(i, k) {
    int nex = to[now];
    now = nex;
  }
  cout << now << endl;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<vi> vvi;

const int mod = 1e9 + 7;
const int inf = 2e9 + 5;
const int N = 1e5 + 5;

ll n, k, a[N];
bool visited[N];

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  cin >> n >> k;
  for (int i = 1; i <= n; i++)
    cin >> a[i];

  int ptr = 1, c = 0, period = -1, ptr1;
  vi cycle(n + 1);

  while (true) {
    if (visited[ptr]) {
      period = c - cycle[ptr];
      ptr1 = ptr;
      break;
    }

    cycle[ptr] = c;
    visited[ptr] = true;

    ptr = a[ptr];
    c += 1;
  }

  if (k < c) {
    for (int i = 1; i <= n; i++) {
      if (cycle[i] == k) {
        cout << i << "\n";
        return 0;
      }
    }
  }

  k -= c;
  k %= period;

  ptr = ptr1;
  c = 0;

  while (true) {
    if (c == k) {
      cout << ptr << "\n";
      return 0;
    }
    ptr = a[ptr];
    c += 1;
  }

  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<vi> vvi;

const int mod = 1e9 + 7;
const int inf = 2e9 + 5;
const int N = 2e5 + 5;

ll n, k, a[N];
bool visited[N];

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  cin >> n >> k;
  for (int i = 1; i <= n; i++)
    cin >> a[i];

  int ptr = 1, c = 0, period = -1, ptr1;
  vi cycle(n + 1);

  while (true) {
    if (visited[ptr]) {
      period = c - cycle[ptr];
      ptr1 = ptr;
      break;
    }

    cycle[ptr] = c;
    visited[ptr] = true;

    ptr = a[ptr];
    c += 1;
  }

  if (k < c) {
    for (int i = 1; i <= n; i++) {
      if (cycle[i] == k) {
        cout << i << "\n";
        return 0;
      }
    }
  }

  k -= c;
  k %= period;

  ptr = ptr1;
  c = 0;

  while (true) {
    if (c == k) {
      cout << ptr << "\n";
      return 0;
    }
    ptr = a[ptr];
    c += 1;
  }

  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
  ios_base ::sync_with_stdio(false);
  int n = 0;
  long long k = 0;
  cin >> n >> k;
  vector<int> p(n + 2, 0);
  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
  }
  vector<int> used(n + 2, -1);
  used[0] = 0;
  int cp = 0;
  int ct = 0;
  while (k > 0) {
    k--;
    ct++;
    cp = p[cp];
    if (used[cp] != -1) {
      break;
    }
    used[cp] = ct;
  }
  k %= (ct - used[cp]);
  while (k > 0) {
    k--;
    cp = p[cp];
  }
  cout << cp + 1;
  return 0;
}

Fixed submission:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
  ios_base ::sync_with_stdio(false);
  int n = 0;
  long long k = 0;
  cin >> n >> k;
  vector<int> p(n + 2, 0);
  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
  }
  vector<int> used(n + 2, -1);
  used[0] = 0;
  int cp = 0;
  int ct = 0;
  while (k > 0) {
    k--;
    ct++;
    cp = p[cp];
    if (used[cp] != -1) {
      break;
    }
    used[cp] = ct;
  }
  if (k != 0)
    k %= (ct - used[cp]);
  while (k > 0) {
    k--;
    cp = p[cp];
  }
  cout << cp + 1;
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;
long long dp[60][200005];
int main() {
  long long n, k;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> dp[0][i];
    dp[0][i]--;
  }
  for (int i = 0; i < 60; i++) {
    for (int j = 0; j < n; j++) {
      dp[i + 1][j] = dp[i][dp[i][j]];
    }
  }
  long long ans = 0;
  for (int i = 59; i >= 0; i--) {
    long long l = 1ll << i;
    if (l <= k) {
      k -= l;
      ans = dp[i][ans];
    }
  }
  cout << ans + 1 << endl;
  return 0;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;
long long dp[60][200005];
int main() {
  long long n, k;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> dp[0][i];
    dp[0][i]--;
  }
  for (int i = 0; i < 59; i++) {
    for (int j = 0; j < n; j++) {
      dp[i + 1][j] = dp[i][dp[i][j]];
    }
  }
  long long ans = 0;
  for (int i = 59; i >= 0; i--) {
    long long l = 1ll << i;
    if (l <= k) {
      k -= l;
      ans = dp[i][ans];
    }
  }
  cout << ans + 1 << endl;
  return 0;
}
Problem p02684 (Python)

Buggy submission (status: Runtime Error):
n, k = list(map(int, input().split()))
a_list = list(map(int, input().split()))

START = 1
# 訪れたタイミング
town_with_i = {START: 0}
# 現在地
current = START
# 既に訪れたことある街(巡回の判定に使う)
known_towns = set([START])
i = 0
for _ in range(k):
    i += 1
    # 現在地
    current = a_list[current - 1]

    # 既に来たことがあるということは巡回している
    if current in known_towns:
        break

    # メモ
    town_with_i[current] = i
    known_towns.add(current)

# 巡回までのステップ数
first_step = town_with_i[current]
# 1周するのに必要なステップ数
r = i - town_with_i[current]

# print(town_with_i)
# print(current)
# print(i)
# print(r)

loop_num = (k - first_step) % r

for i in range(loop_num):
    current = a_list[current - 1]

print(current)


Fixed submission:
n, k = list(map(int, input().split()))
a_list = list(map(int, input().split()))

START = 1
# 訪れたタイミング
town_with_i = {START: 0}
# 現在地
current = START
# 既に訪れたことある街(巡回の判定に使う)
known_towns = set([START])
i = 0
for _ in range(k):
    i += 1
    # 現在地
    current = a_list[current - 1]

    # 既に来たことがあるということは巡回している
    if current in known_towns:
        break

    # メモ
    town_with_i[current] = i
    known_towns.add(current)

# 巡回までのステップ数
first_step = town_with_i[current]
# 1周するのに必要なステップ数
r = i - town_with_i[current]

# print(town_with_i)
# print(current)
# print(i)
# print(r)

loop_num = (k - first_step) % r if r > 0 else (k - first_step)

for i in range(loop_num):
    current = a_list[current - 1]

print(current)
Problem p02684 (Python)

Buggy submission (status: Runtime Error):
n, k = map(int, input().split())
a = list(map(int, input().split()))
rec = [0]
i = 0
flag = [0 for _ in range(n + 1)]
while True:
    if flag[rec[i]] == 0:
        flag[rec[i]] = 1
        rec.append(a[rec[i]] - 1)
    else:
        start = rec.index(a[rec[i]] - 1)
        loop = rec[start:]
        pre = rec[:start]
        break
    i += 1
count = (k - len(pre)) % len(loop)
if k < len(pre):
    print(loop[k])
else:
    print(loop[count] + 1)


Fixed submission:
n, k = map(int, input().split())
a = list(map(int, input().split()))
rec = [0]
i = 0
flag = [0 for _ in range(n + 1)]
while True:
    if flag[rec[i]] == 0:
        flag[rec[i]] = 1
        rec.append(a[rec[i]] - 1)
    else:
        start = rec.index(a[rec[i]] - 1)
        loop = rec[start:]
        pre = rec[:start]
        break
    i += 1
count = (k - len(pre)) % len(loop)
if k <= len(pre):
    print(pre[k] + 1)
else:
    print(loop[count] + 1)
Problem p02684 (Python)

Buggy submission (status: Time Limit Exceeded):
#!/usr/bin/env python3

import numpy as np


# def input():
#     return sys.stdin.readline().rstrip()


def main():
    n, k = map(int, input().split())

    warps = list(map(int, input().split()))
    warps = [0] + warps
    warps = np.array(warps, dtype=int)

    dp = np.zeros((k.bit_length() + 1, n + 1), dtype=int)

    dp[0, :] = warps

    for h in range(1, len(dp)):
        for j in range(len(dp[0] + 1)):
            dp[h][j] = dp[h - 1][dp[h - 1][j]]

    node = 1
    # for i in reversed(range(k.bit_length())):
    for i in range(k.bit_length(), -1, -1):
        if k >> i & 1:
            node = dp[i][node]

    print(node)


main()


Fixed submission:
#!/usr/bin/env python3

import numpy as np


# def input():
#     return sys.stdin.readline().rstrip()


def main():
    n, k = map(int, input().split())

    warps = list(map(int, input().split()))
    warps = [0] + warps
    warps = np.array(warps, dtype=int)

    dp = np.zeros((k.bit_length() + 1, n + 1), dtype=int)

    dp[0, :] = warps

    for h in range(1, len(dp)):
        # dp[h] = dp[h - 1][dp[h - 1]]
        dp[h] = np.take(dp[h - 1], dp[h - 1])

    node = 1
    # for i in reversed(range(k.bit_length())):
    for i in range(k.bit_length(), -1, -1):
        if k >> i & 1:
            node = dp[i][node]

    print(node)


main()
Problem p02684 (Python)

Buggy submission (status: Runtime Error):
import sys

sys.setrecursionlimit(10**7)
f_inf = float("inf")
mod = 10**9 + 7


def resolve():
    n, k = map(int, input().split())
    A = list(map(int, input().split()))

    tree = [[] for _ in range(n)]
    for idx, a in enumerate(A):
        tree[idx].append(a - 1)

    start = []
    depth = [0 for _ in range(n)]

    def dfs(v, p, d, cnt):
        depth[v] = d
        for u in tree[v]:
            if u == p:
                continue

            if visited[u]:
                start.append([u + 1, depth[u], cnt + 1])
                return
            else:
                visited[u] = True
                dfs(u, v, d + 1, cnt + 1)
        return

    visited = [False for _ in range(n)]
    visited[0] = True
    dfs(0, -1, 0, 0)

    if k <= start[0][1]:
        print(depth.index(k) + 1)
    else:
        cnt = (k - start[0][1]) % (start[0][2] - start[0][1])
        res = start[0][1] + cnt
        print(depth.index(res) + 1)


if __name__ == "__main__":
    resolve()


Fixed submission:
import sys

sys.setrecursionlimit(10**7)
f_inf = float("inf")
mod = 10**9 + 7


def resolve():
    n, k = map(int, input().split())
    A = list(map(int, input().split()))

    tree = [[] for _ in range(n)]
    for idx, a in enumerate(A):
        tree[idx].append(a - 1)

    start = []
    depth = [0 for _ in range(n)]

    def dfs(v, p, d, cnt):
        depth[v] = d
        for u in tree[v]:
            if visited[u]:
                start.append([u + 1, depth[u], cnt + 1])
                return
            else:
                visited[u] = True
                dfs(u, v, d + 1, cnt + 1)
        return

    visited = [False for _ in range(n)]
    visited[0] = True
    dfs(0, -1, 0, 0)

    if k <= start[0][1]:
        print(depth.index(k) + 1)
    else:
        cnt = (k - start[0][1]) % (start[0][2] - start[0][1])
        res = start[0][1] + cnt
        print(depth.index(res) + 1)


if __name__ == "__main__":
    resolve()
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define mod 1000000009
#define ll long long
using namespace std;
long long int n, num, a[20005], vis[20005];
int main() {
  scanf("%lld%lld", &n, &num);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &a[i]), vis[i] = 0;
  long long int pos1 = 1, pos2;
  while (vis[pos1] != 1) {
    vis[pos1] = 1;
    pos1 = a[pos1];
  }
  pos2 = pos1;
  for (int j = 1; j <= n; j++)
    vis[j] = 0;
  int t = 0;
  while (vis[pos2] != 1) {
    vis[pos2] = 1;
    t++;
    pos2 = a[pos2];
  }
  int b = 0;
  pos2 = 1;
  while (1) {
    if (pos1 == pos2)
      break;
    pos2 = a[pos2], b++;
  }
  int c = 0;
  if (num <= b) {
    pos2 = 1;
    while (1) {
      if (num == c)
        break;
      pos2 = a[pos2], c++;
    }
    printf("%d\n", pos2);
    return 0;
  }
  num -= b;
  num %= t;
  pos2 = pos1;
  c = 0;
  while (1) {
    if (num == c)
      break;
    pos2 = a[pos2], c++;
  }
  printf("%d\n", pos2);
  return 0;
}


Fixed submission:
#include <bits/stdc++.h>
#define mod 1000000009
#define ll long long
using namespace std;
long long int n, num, a[200005], vis[200005];
int main() {
  scanf("%lld%lld", &n, &num);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &a[i]), vis[i] = 0;
  long long int pos1 = 1, pos2;
  while (vis[pos1] != 1) {
    vis[pos1] = 1;
    pos1 = a[pos1];
  }
  pos2 = pos1;
  for (int j = 1; j <= n; j++)
    vis[j] = 0;
  int t = 0;
  while (vis[pos2] != 1) {
    vis[pos2] = 1;
    t++;
    pos2 = a[pos2];
  }
  int b = 0;
  pos2 = 1;
  while (1) {
    if (pos1 == pos2)
      break;
    pos2 = a[pos2], b++;
  }
  int c = 0;
  if (num <= b) {
    pos2 = 1;
    while (1) {
      if (num == c)
        break;
      pos2 = a[pos2], c++;
    }
    printf("%d\n", pos2);
    return 0;
  }
  num -= b;
  num %= t;
  pos2 = pos1;
  c = 0;
  while (1) {
    if (num == c)
      break;
    pos2 = a[pos2], c++;
  }
  printf("%d\n", pos2);
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
#define chmax(x, y) x = max(x, y);
const int di[] = {-1, 0, 1, 0};
const int dj[] = {0, -1, 0, 1};
const int INF = 1001001001;

int main() {
  int n;
  ll k;
  cin >> n >> k;
  vector<int> a(n);
  rep(i, n) cin >> a[i];

  vector<int> s;
  vector<int> ord(n + 1, -1);
  int c = 0, l = 0;

  int v = 1;
  while (ord[v] != -1) {
    ord[v] = s.size();
    s.push_back(v);
    v = a[v - 1];
  }
  c = s.size() - ord[v];
  l = ord[v];

  if (k < l)
    cout << s[k] << endl;
  else {
    k -= l;
    k %= c;
    cout << s[l + k] << endl;
  }
  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
#define chmax(x, y) x = max(x, y);
const int di[] = {-1, 0, 1, 0};
const int dj[] = {0, -1, 0, 1};
const int INF = 1001001001;

int main() {
  int n;
  ll k;
  cin >> n >> k;
  vector<int> a(n);
  rep(i, n) cin >> a[i];

  vector<int> s;
  vector<int> ord(n + 1, -1);
  int c = 0, l = 0;

  int v = 1;
  while (ord[v] == -1) {
    ord[v] = s.size();
    s.push_back(v);
    v = a[v - 1];
  }
  c = s.size() - ord[v];
  l = ord[v];

  if (k < l)
    cout << s[k] << endl;
  else {
    k -= l;
    k %= c;
    cout << s[l + k] << endl;
  }
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;

int main() {
  long long n, k;
  cin >> n >> k;
  vector<int> a(n);
  for (int i = 0; i < n; i++)
    cin >> a[i];

  int cnt = 1, tmp, aa;
  vector<int> check(n, 0);
  check[0] = 1;
  for (long long i = 1; i <= k; i++) {
    cnt = a[cnt - 1];
    if (check[cnt - 1] == 0)
      check[cnt - 1] = i + 1;
    else {
      tmp = i + 1 - check[cnt - 1];
      aa = i - tmp;
      // cout<<tmp<<' '<<cnt<<' '<<aa<<endl;
      break;
    }
  }
  tmp = (k - aa) % tmp;
  for (int i = 0; i < tmp; i++) {
    cnt = a[cnt - 1];
  }
  cout << cnt << endl;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;

int main() {
  long long n, k;
  cin >> n >> k;
  vector<int> a(n);
  for (int i = 0; i < n; i++)
    cin >> a[i];

  int cnt = 1, tmp = k, aa = 0;
  vector<int> check(n, 0);
  check[0] = 1;
  for (long long i = 1; i <= k; i++) {
    cnt = a[cnt - 1];
    if (check[cnt - 1] == 0)
      check[cnt - 1] = i + 1;
    else {
      tmp = i + 1 - check[cnt - 1];
      aa = i - tmp;
      // cout<<tmp<<' '<<cnt<<' '<<aa<<endl;
      break;
    }
  }
  tmp = (k - aa) % tmp;
  for (int i = 0; i < tmp; i++) {
    cnt = a[cnt - 1];
  }
  cout << cnt << endl;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

int main() {

  int n;
  long long int k;
  cin >> n >> k;

  int a[n];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    a[i]--;
  }

  int b[n + 1];
  vector<int> c;

  int d = 0;

  for (int i = 0; i < n + 3; i++) {
    b[d]++;
    c.push_back(d);
    if (b[d] == 2)
      break;
    d = a[d];
  }

  int p;
  p = c.size();
  int q = 0;

  for (int i = 0; i < p; i++) {
    if (c[i] == c[p - 1]) {
      q = i;
      break;
    }
  }

  if (k < p)
    cout << c[k] + 1 << endl;
  else
    cout << c[q + (k - p + 1) % (p - q - 1)] + 1 << endl;
}

Fixed submission:
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

int main() {

  int n;
  long long int k;
  cin >> n >> k;

  int a[n];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    a[i]--;
  }

  int b[n + 1] = {};
  vector<int> c;

  int d = 0;

  for (int i = 0; i < n + 3; i++) {
    b[d]++;
    c.push_back(d);
    if (b[d] == 2)
      break;
    d = a[d];
  }

  int p;
  p = c.size();
  int q = 0;

  for (int i = 0; i < p; i++) {
    if (c[i] == c[p - 1]) {
      q = i;
      break;
    }
  }

  if (k < p)
    cout << c[k] + 1 << endl;
  else
    cout << c[q + (k - p + 1) % (p - q - 1)] + 1 << endl;
}
Problem p02684 (C++)

Buggy submission (status: Time Limit Exceeded):
/*
 *       ~ AtCoder  Botay ~
 *        code by kazalika
 */

#include <bits/stdc++.h>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  long long k;
  cin >> n >> k;
  vector<int> a(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
    a[i]--;
  }
  if (a[0] == 0) {
    cout << 1;
    return 0;
  }
  vector<long long> timer(n);
  long long nn = 0, t = 0;
  while (timer[nn] < k || !timer[nn]) {
    timer[nn] = t;
    if (timer[nn] == k || a[nn] == nn) {
      cout << nn + 1;
      return 0;
    }
    nn = a[nn];
    t++;
  }
  k -= timer[nn];
  assert(k >= 0);
  if (!k || a[nn] == nn) {
    cout << nn + 1;
    return 0;
  }
  long long st = nn, cn = 1;
  nn = a[nn];
  vector<long long> v = {st};
  while (st != nn) {
    v.push_back(nn);
    nn = a[nn];
    cn++;
  }
  assert(v.size() == cn);
  cout << v[k % cn] + 1;
}

Fixed submission:
/*
 *       ~ AtCoder  Botay ~
 *        code by kazalika
 */

#include <bits/stdc++.h>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  long long k;
  cin >> n >> k;
  vector<int> a(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
    a[i]--;
  }
  if (a[0] == 0) {
    cout << 1;
    return 0;
  }
  vector<long long> timer(n);
  long long nn = 0, t = 0;
  while (!timer[nn]) {
    timer[nn] = t;
    if (timer[nn] == k || a[nn] == nn) {
      cout << nn + 1;
      return 0;
    }
    nn = a[nn];
    t++;
  }
  k -= timer[nn];
  assert(k >= 0);
  if (!k || a[nn] == nn) {
    cout << nn + 1;
    return 0;
  }
  long long st = nn, cn = 1;
  nn = a[nn];
  vector<long long> v = {st};
  while (st != nn) {
    v.push_back(nn);
    nn = a[nn];
    cn++;
  }
  assert(v.size() == cn);
  cout << v[k % cn] + 1;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define ll unsigned long long
using namespace std;
const int maxn = 1e5 + 10;

ll arr[maxn], vis[maxn];
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  ll n, k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++)
    cin >> arr[i];
  int acout = 0, cur = 1;
  vector<int> v;
  while (1) {
    if (vis[cur])
      break;
    else {
      acout++, vis[cur] = 1;
      v.push_back(cur);
      cur = arr[cur];
    }
  }
  // for(int i=0;i<v.size();i++) cout<<v[i]<<" ";
  // cout<<"debug "<<cur<<endl;
  int cal = 0, i = 0;
  if (v.size() > k) {
    cout << v[k] << endl;
    return 0;
  }
  while (1) {
    if (v[i] != cur)
      cal++, acout--, v.erase(v.begin());
    else
      break;
  }
  if (cal > 0)
    k -= cal;
  // for(int i=0;i<v.size();i++) cout<<v[i]<<" ";
  // cout<<endl;
  if (acout == 0) {
    cout << v[v.size() - 1] << endl;
    return 0;
  }
  cout << v[k % acout] << endl;
  return 0;
}

Fixed submission:
#include <bits/stdc++.h>
#define ll unsigned long long
using namespace std;
const int maxn = 2e5 + 10;

ll arr[maxn], vis[maxn];
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  ll n, k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++)
    cin >> arr[i];
  int acout = 0, cur = 1;
  vector<int> v;
  while (1) {
    if (vis[cur])
      break;
    else {
      acout++, vis[cur] = 1;
      v.push_back(cur);
      cur = arr[cur];
    }
  }
  // for(int i=0;i<v.size();i++) cout<<v[i]<<" ";
  // cout<<"debug "<<cur<<endl;
  int cal = 0, i = 0;
  if (v.size() > k) {
    cout << v[k] << endl;
    return 0;
  }
  while (1) {
    if (v[i] != cur)
      cal++, acout--, v.erase(v.begin());
    else
      break;
  }
  if (cal > 0)
    k -= cal;
  // for(int i=0;i<v.size();i++) cout<<v[i]<<" ";
  // cout<<endl;
  if (acout == 0) {
    cout << v[v.size() - 1] << endl;
    return 0;
  }
  cout << v[k % acout] << endl;
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>

using namespace std;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
#define ll long long
#define sz(a) int((a).size())
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define tr(c, i) for (typeof((c)).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c, x) ((c).find(x) != (c).end())
#define cpresent(c, x) (find(all(c), x) != (c).end())
#define fastio                                                                 \
  ios_base::sync_with_stdio(false);                                            \
  cin.tie(0);                                                                  \
  cout.tie(0);
#define hell 1000000007
#define PI 3.141592653589793

int main() {
  fastio;
  int testcases = 1;
  // cin>>testcases;
  while (testcases--) {
    int n;
    ll k;
    cin >> n >> k;
    vi towns(n + 1);
    for (int i = 1; i <= n; i++)
      cin >> towns[i];
    vi visited;
    int current = 1;
    int used = 0;
    while (!cpresent(visited, towns[current])) {
      visited.pb(towns[current]);
      current = towns[current];
      ++used;
      if (used >= k)
        break;
    }

    if (used < k) {
      int pos;
      for (int i = 0; i < sz(visited); i++) {
        if (visited[i] == towns[current]) {
          pos = i;
          break;
        }
      }
      int period = used - pos;
      int rem = (k - used) % period;
      if (rem == 0)
        rem = period;
      current = visited[pos + rem - 1];
    }
    cout << current;
    cout << "\n";
  }
  return 0;
}


Fixed submission:
#include <bits/stdc++.h>

using namespace std;

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
#define ll long long
#define sz(a) int((a).size())
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define tr(c, i) for (typeof((c)).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c, x) ((c).find(x) != (c).end())
#define cpresent(c, x) (find(all(c), x) != (c).end())
#define fastio                                                                 \
  ios_base::sync_with_stdio(false);                                            \
  cin.tie(0);                                                                  \
  cout.tie(0);
#define hell 1000000007
#define PI 3.141592653589793

int main() {
  fastio;
  int testcases = 1;
  // cin>>testcases;
  while (testcases--) {
    int n;
    ll k;
    cin >> n >> k;
    vi towns(n + 1);
    for (int i = 1; i <= n; i++)
      cin >> towns[i];
    vi visited;
    int current = 1;
    int used = 0;
    while (used < n) {
      visited.pb(towns[current]);
      current = towns[current];
      ++used;
      if (used >= k)
        break;
    }

    if (used < k) {
      int pos;
      for (int i = 0; i < sz(visited); i++) {
        if (visited[i] == towns[current]) {
          pos = i;
          break;
        }
      }
      int period = used - pos;
      int rem = (k - used) % period;
      if (rem == 0)
        rem = period;
      current = visited[pos + rem - 1];
    }
    cout << current;
    cout << "\n";
  }
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;
int main() {
  vector<long long> firstpath;
  vector<long long> roop;
  long long N;
  long long K;
  ;
  cin >> N >> K;
  long long A[N], visited[N];
  for (int i = 0; i < N; i++) {
    cin >> A[i];
    A[i]--;
    visited[i] = 0;
  }
  long long now, roopstart;
  now = A[0];
  visited[0] = 1;
  while (1) {
    if (visited[now] > 0) {
      roopstart = now;
      break;
    } else {
      visited[now] = 1;
      now = A[now];
    }
  }
  now = 0;
  while (1) {
    if (now == roopstart) {
      break;
    } else {
      firstpath.push_back(now);
      now = A[now];
    }
  }
  now = roopstart;
  roop.push_back(roopstart);
  while (1) {
    now = A[now];
    if (now == roopstart)
      break;
    else {
      roop.push_back(now);
    }
  }
  long long ans;
  if (K <= firstpath.size()) {
    ans = firstpath.at(K);
  } else {
    K -= firstpath.size();
    K %= roop.size();
    ans = roop.at(K);
  }
  cout << ans + 1;
  return 0;
}


Fixed submission:
#include <bits/stdc++.h>
using namespace std;
int main() {
  vector<long long> firstpath;
  vector<long long> roop;
  long long N;
  long long K;
  ;
  cin >> N >> K;
  long long A[N], visited[N];
  for (int i = 0; i < N; i++) {
    cin >> A[i];
    A[i]--;
    visited[i] = 0;
  }
  long long now, roopstart;
  now = A[0];
  visited[0] = 1;
  while (1) {
    if (visited[now] > 0) {
      roopstart = now;
      break;
    } else {
      visited[now] = 1;
      now = A[now];
    }
  }
  now = 0;
  while (1) {
    if (now == roopstart) {
      break;
    } else {
      firstpath.push_back(now);
      now = A[now];
    }
  }
  now = roopstart;
  roop.push_back(roopstart);
  while (1) {
    now = A[now];
    if (now == roopstart)
      break;
    else {
      roop.push_back(now);
    }
  }
  long long ans;
  if (K < firstpath.size()) {
    ans = firstpath.at(K);
  } else {
    K -= firstpath.size();
    K %= roop.size();
    ans = roop.at(K);
  }
  cout << ans + 1;
  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
using namespace std;

#define COUT(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl
template <class T1, class T2> ostream &operator<<(ostream &s, pair<T1, T2> P) {
  return s << '<' << P.first << ", " << P.second << '>';
}
template <class T> ostream &operator<<(ostream &s, deque<T> P) {
  for (int i = 0; i < P.size(); ++i) {
    if (i > 0) {
      s << " ";
    }
    s << P[i];
  }
  return s;
}
template <class T> ostream &operator<<(ostream &s, vector<vector<T>> P) {
  for (int i = 0; i < P.size(); ++i) {
    s << endl << P[i];
  }
  return s << endl;
}
template <class T> ostream &operator<<(ostream &s, set<T> P) {
  for (auto it : P) {
    s << "<" << it << "> ";
  }
  return s << endl;
}

int main() {
  int N;
  long long K;
  cin >> N >> K;
  vector<int> A(N);
  for (int i = 0; i < N; ++i)
    cin >> A[i], --A[i];

  deque<int> a;                // 繰り返しの部分
  vector<bool> seen(N, false); // 一度見たかどうか
  int cur = 0;
  while (true) {
    // 一度通った頂点を見つけたときの処理
    if (seen[cur]) {
      while (a[0] != cur) {
        // 最初の余計な数手分を除去する
        --K;
        a.pop_front();

        // 繰り返す前に K が限界になったらリターン
        if (K == 0)
          return a[0] + 1;
      }
      break;
    }
    // 最初は愚直にシミュレーションしつつ、履歴をメモしていく
    a.push_back(cur);
    seen[cur] = true;
    cur = A[cur];
  }
  cout << a[K % a.size()] + 1 << endl;
}

Fixed submission:
#include <bits/stdc++.h>
using namespace std;

#define COUT(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl
template <class T1, class T2> ostream &operator<<(ostream &s, pair<T1, T2> P) {
  return s << '<' << P.first << ", " << P.second << '>';
}
template <class T> ostream &operator<<(ostream &s, deque<T> P) {
  for (int i = 0; i < P.size(); ++i) {
    if (i > 0) {
      s << " ";
    }
    s << P[i];
  }
  return s;
}
template <class T> ostream &operator<<(ostream &s, vector<vector<T>> P) {
  for (int i = 0; i < P.size(); ++i) {
    s << endl << P[i];
  }
  return s << endl;
}
template <class T> ostream &operator<<(ostream &s, set<T> P) {
  for (auto it : P) {
    s << "<" << it << "> ";
  }
  return s << endl;
}

int main() {
  int N;
  long long K;
  cin >> N >> K;
  vector<int> A(N);
  for (int i = 0; i < N; ++i)
    cin >> A[i], --A[i];

  deque<int> a;                // 繰り返しの部分
  vector<bool> seen(N, false); // 一度見たかどうか
  int cur = 0;
  while (true) {
    // 一度通った頂点を見つけたときの処理
    if (seen[cur]) {
      while (a[0] != cur) {
        // 最初の余計な数手分を除去する
        --K;
        a.pop_front();

        // 繰り返す前に K が限界になったらリターン
        if (K == 0) {
          cout << a[0] + 1 << endl;
          return 0;
        }
      }
      break;
    }
    // 最初は愚直にシミュレーションしつつ、履歴をメモしていく
    a.push_back(cur);
    seen[cur] = true;
    cur = A[cur];
  }
  cout << a[K % a.size()] + 1 << endl;
}
Problem p02684 (Python)

Buggy submission (status: Time Limit Exceeded):
[n, k], [*a] = [[*map(int, t.split())] for t in open(0)]
ans = 1
for _ in range(k):
    ans = a[ans - 1]
print(ans)


Fixed submission:
[n, k], [*a] = [[*map(int, t.split())] for t in open(0)]
count = 0
visited = dict()
tmp = 1
while count < k:
    visited[tmp] = count
    count += 1
    tmp = a[tmp - 1]
    if tmp in visited:
        break
if count < k:
    k = (k - count) % (count - visited[tmp])
    for _ in range(k):
        tmp = a[tmp - 1]
print(tmp)
Problem p02684 (Python)

Buggy submission (status: Runtime Error):
N, K = map(int, input().split())
X = list(map(int, input().split()))
town = []
dic = {}
i = 0
j = 0
while i not in dic and j < K:
    dic[i] = j
    town.append(i)
    i = X[i] - 1
    j += 1

if j == K:
    print(town[K] + 1)

else:
    num = dic[i]
    loop = j - num
    print(town[((K - num) % loop) + num] + 1)


Fixed submission:
N, K = map(int, input().split())
X = list(map(int, input().split()))
town = []
dic = {}
i = 0
j = 0
while i not in dic and j < K:
    dic[i] = j
    town.append(i)
    i = X[i] - 1
    j += 1

if j == K:
    print(i + 1)

else:
    num = dic[i]
    loop = j - num
    print(town[((K - num) % loop) + num] + 1)
Problem p02684 (Python)

Buggy submission (status: Runtime Error):
n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))

visited_city = {1: 0}
visited_city_inv = {0: 1}

now = 1
num = 0
while True:
    next_city = arr[now - 1]
    num += 1
    if next_city not in visited_city:
        visited_city[next_city] = num
        visited_city_inv[num] = next_city
        now = next_city
    else:
        break

if k < num:
    ans = visited_city[k]
else:
    x = visited_city[next_city]
    period = num - x
    ans = visited_city_inv[x + (k - x) % period]

print(ans)
# print(visited_city)


Fixed submission:
n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))

visited_city = {1: 0}
visited_city_inv = {0: 1}

now = 1
num = 0
while True:
    next_city = arr[now - 1]
    num += 1
    if next_city not in visited_city:
        visited_city[next_city] = num
        visited_city_inv[num] = next_city
        now = next_city
    else:
        break

if k < num:
    ans = visited_city_inv[k]
else:
    x = visited_city[next_city]
    period = num - x
    ans = visited_city_inv[x + (k - x) % period]

print(ans)
# print(visited_city)
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#define ll long long
#define ar array
#define nl '\n'
#define AC                                                                     \
  ios_base::sync_with_stdio(0);                                                \
  cin.tie(NULL);
using namespace std;
const int M = 1e9 + 7;
const int N = 1e5;

int cur_pos[N + 5];
int tele[N + 5];
ll pred[N + 5];

int main() {
  AC int n;
  ll k;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> tele[i];
    tele[i]--;
  }
  memset(pred, -1, sizeof(pred));

  cur_pos[0] = 0;
  pred[0] = 0;
  for (ll i = 1; i <= k; i++) {
    cur_pos[i] = tele[cur_pos[i - 1]];
    if (pred[cur_pos[i]] != -1) {
      // city already visited
      ll cycle_len = i - pred[cur_pos[i]];
      ll last_steps = (k - i) % cycle_len;
      ll last_pos = cur_pos[pred[cur_pos[i]] + last_steps];
      cout << last_pos + 1 << endl;
      return 0;
    } else
      pred[cur_pos[i]] = i;
  }
  cout << cur_pos[k] + 1 << endl;
}

Fixed submission:
#include <bits/stdc++.h>
#define ll long long
#define ar array
#define nl '\n'
#define AC                                                                     \
  ios_base::sync_with_stdio(0);                                                \
  cin.tie(NULL);
using namespace std;
const int M = 1e9 + 7;
const int N = 2 * 1e5;

int cur_pos[N + 5];
int tele[N + 5];
ll pred[N + 5];

int main() {
  AC int n;
  ll k;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> tele[i];
    tele[i]--;
  }
  memset(pred, -1, sizeof(pred));

  cur_pos[0] = 0;
  pred[0] = 0;
  for (ll i = 1; i <= k; i++) {
    cur_pos[i] = tele[cur_pos[i - 1]];
    if (pred[cur_pos[i]] != -1) {
      // city already visited
      ll cycle_len = i - pred[cur_pos[i]];
      ll last_steps = (k - i) % cycle_len;
      ll last_pos = cur_pos[pred[cur_pos[i]] + last_steps];
      cout << last_pos + 1 << endl;
      return 0;
    } else
      pred[cur_pos[i]] = i;
  }
  cout << cur_pos[k] + 1 << endl;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

vector<int> g;
bool seen[200001];
vector<int> go;

int dfs(int s) {
  if (seen[s])
    return s;
  seen[s] = true;
  go.push_back(s);
  dfs(g[s]);
}

int main() {
  int n;
  ll k;
  cin >> n >> k;
  g.resize(n);

  rep(i, n) {
    int tmp;
    cin >> tmp;
    g[i] = (tmp - 1);
  }

  int loop;
  loop = dfs(0);
  int start;
  int mod;
  int len;
  len = go.size();

  for (int i = 0; i < len; i++) {
    if (go[i] == loop)
      start = i;
    mod = len - start;
  }

  vector<int> to(mod);
  for (int j = start; j < len; j++) {
    to[j % mod] = go[j];
  }

  if (k < len)
    cout << go[int(k)] + 1 << endl;
  else {
    k %= (ll)mod;
    cout << to[int(k)] + 1 << endl;
  }

  return 0;
}

Fixed submission:
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

vector<int> g;
bool seen[200001];
vector<int> go;

int dfs(int s) {
  if (seen[s])
    return s;
  seen[s] = true;
  go.push_back(s);
  return dfs(g[s]);
}

int main() {
  int n;
  ll k;
  cin >> n >> k;
  g.resize(n);

  rep(i, n) {
    int tmp;
    cin >> tmp;
    g[i] = (tmp - 1);
  }

  int loop;
  loop = dfs(0);
  int start;
  int mod;
  int len;
  len = go.size();

  for (int i = 0; i < len; i++) {
    if (go[i] == loop)
      start = i;
    mod = len - start;
  }

  vector<int> to(mod);
  for (int j = start; j < len; j++) {
    to[j % mod] = go[j];
  }

  if (k < len)
    cout << go[int(k)] + 1 << endl;
  else {
    k %= (ll)mod;
    cout << to[int(k)] + 1 << endl;
  }

  return 0;
}
Problem p02684 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
typedef pair<ll, ll> P;
typedef priority_queue<P, vector<P>, greater<P>> P_queue;

#define REP(i, a, b) for (int i = (int)a; i < (int)b; i++)
#define rep(i, n) REP(i, 0, n)
#define pb push_back
#define mp make_pair
#define ALL(a) a.begin(), a.end()
#define SORT(a) sort(ALL(a))
#define U_ERASE(V) V.erase(unique(ALL(V)), V.end());

const ll MOD = 998244353;
const ll mod = 1000000007;
const ll INF = 1e15;
vec dx = {1, 0, -1, 0};
vec dy = {0, 1, 0, -1};

vec d;
ll memo[200010];
bool used[200010];
ll Loop;
ll Solve(ll x, ll K) {

  // cout<<K<<' '<<memo[x]<<' '<<x<<endl;
  if (K == 0)
    return x;
  if (!used[x]) {
    memo[x] = K;
    used[x] = true;
    return Solve(d[x], K - 1);
  }
  if (K >= memo[x] - K) {
    Loop = memo[x] - K;
    return Solve(x, K % Loop);
  }
  return Solve(d[x], K - 1);
}
void init() {
  rep(i, 200010) memo[i] = INF;
  rep(i, 200010) used[i] = false;
  return;
}

int main() {
  init();
  ll N, K;
  cin >> N >> K;
  rep(i, N) {
    ll x;
    cin >> x;
    x--;
    d.pb(x);
  }
  Solve(0, 300000);
  // cout<<Loop<<endl;
  init();
  ll P = (N / Loop);
  P++;
  P *= Loop;
  K %= Loop;
  K += P;
  cout << Solve(0, K) + 1 << endl;
}

Fixed submission:
#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
typedef pair<ll, ll> P;
typedef priority_queue<P, vector<P>, greater<P>> P_queue;

#define REP(i, a, b) for (int i = (int)a; i < (int)b; i++)
#define rep(i, n) REP(i, 0, n)
#define pb push_back
#define mp make_pair
#define ALL(a) a.begin(), a.end()
#define SORT(a) sort(ALL(a))
#define U_ERASE(V) V.erase(unique(ALL(V)), V.end());

const ll MOD = 998244353;
const ll mod = 1000000007;
const ll INF = 1e15;
vec dx = {1, 0, -1, 0};
vec dy = {0, 1, 0, -1};

vec d;
ll memo[200010];
bool used[200010];
ll Loop;
ll Solve(ll x, ll K) {

  // cout<<K<<' '<<memo[x]<<' '<<x<<endl;
  if (K == 0)
    return x;
  if (!used[x]) {
    memo[x] = K;
    used[x] = true;
    return Solve(d[x], K - 1);
  }
  if (K >= memo[x] - K) {
    Loop = memo[x] - K;
    return Solve(x, K % Loop);
  }
  return Solve(d[x], K - 1);
}
void init() {
  rep(i, 200010) memo[i] = INF;
  rep(i, 200010) used[i] = false;
  return;
}

int main() {
  init();
  ll N, K;
  cin >> N >> K;
  rep(i, N) {
    ll x;
    cin >> x;
    x--;
    d.pb(x);
  }

  cout << Solve(0, K) + 1 << endl;
}
Problem p02684 (C++)

Buggy submission (status: Time Limit Exceeded):
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;

int main() {
  long n, k, cur = 1, cnt = 1;
  cin >> n >> k;
  vector<long> a(n);
  vector<bool> flag(n, true);
  rep(i, n) cin >> a.at(i);
  bool f = true;
  do {
    k--;
    f &= flag.at(cur - 1);
    flag.at(cur - 1) = false;
    cur = a.at(cur - 1);
  } while (k > 0 && f);
  long temp = a.at(cur - 1);
  while (temp != cur) {
    cnt++;
    temp = a.at(temp - 1);
  }
  k %= cnt;
  rep(i, k) cur = a.at(cur - 1);
  cout << cur << endl;
}

Fixed submission:
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;

int main() {
  long n, k, cur = 1, cnt = 1;
  cin >> n >> k;
  vector<long> a(n);
  vector<bool> flag(n, true);
  rep(i, n) cin >> a.at(i);
  bool f = true;
  do {
    k--;
    f &= flag.at(cur - 1);
    flag.at(cur - 1) = false;
    cur = a.at(cur - 1);
  } while (k > 0 && f);
  long temp = a.at(cur - 1);
  while (k > 0 && temp != cur) {
    cnt++;
    temp = a.at(temp - 1);
  }
  k %= cnt;
  rep(i, k) cur = a.at(cur - 1);
  cout << cur << endl;
}