jiahuimbzuai/CoQuIR huggingface dataset:
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    let aryS = readLine()!.map { String($0) }
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    var ans = 0
    for i in 0..<n / 2{
        if aryS[i] == "W" {
            ans += 1
        }
    }
    print(ans)
}
main()
//  [typescript]
// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [N] = r.nn()

    const s = r.s()
    // const hasR = s.split('').some((c) => c === 'R')
    // const hasW = s.split('').some((c) => c === 'W')

    // if (!hasR || !hasW) {
    //   return 0
    // }

    let si = 0
    let ei = N - 1
    let res = 0

    while (si < ei) {
      while (s[si] === 'R') si++
      while (s[ei] === 'W') ei--
      if (si > ei) break

      si++
      ei--
      res++
    }

    return res
  }

  const _io = (i = 0) => {
    const str: string = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map((v) => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map((line) => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}
//  [typescript]
import * as fs from 'fs';

const input = fs.readFileSync('/dev/stdin', 'utf8');
//const input = fs.readFileSync('./input.txt', 'utf8');

_d(input);

function _d(input: string) {
  const [N, c] = input.split('\n');

  // 特殊ケース（全ての色が同じ）
  const top = c[0];
  let sameAll = true;
  for (const color of c) {
    if (top !== color) {
      sameAll = false;
      break;
    }
  }
  if (sameAll) {
    console.log(0);
    return;
  }

  let redCursor = 0;
  let whiteCursor = c.length - 1;
  let swapped = 0;
  main: while (true) {
    // 左から順に見て白があればカウントアップ
    while (c[redCursor] === 'R') {
      redCursor++;
      // 最後まで到達した
      if (redCursor >= whiteCursor) {
        // console.log('[red] no swap needed');
        break main;
      }
    }

    // 右から順に見て赤があれば続ける
    while (c[whiteCursor] === 'W') {
      whiteCursor--;
      // 最後まで到達した
      if (redCursor >= whiteCursor) {
        // console.log('[white] red found, but no swap needed');
        break main;
      }
    }

    swapped++; // 反転が１回必要
    // console.log(`swap ${redCursor} ${whiteCursor}`);

    redCursor++; // カーソルを進めておく
    whiteCursor--; // カーソルを勧めておく
  }

  console.log(swapped);
}
//  [typescript]
import { readFileSync } from 'fs'

const RED_STONE = 'R'

function main(input: string) {
  const [[n], stones] = input.split('\n').map(v => v.split(''))

  const border = stones.filter(s => s === RED_STONE).length
  const res = stones.slice(border).filter(s => s === RED_STONE).length

  console.log(res)
}

main(readFileSync('/dev/stdin', 'utf8').trim())
//  [typescript]
import { readFileSync } from "fs";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const range = (n: number | bigint) => [...Array(Number(n))].map((_, i) => i);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const tuple = <T extends unknown[]>(...ts: T) => ts;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [cin, nCin, biCin] = (() => {
  const inputs = readFileSync("/dev/stdin", "utf-8").split(/[\n|\s]+/);
  let count = 0;
  const cin = () => inputs[count++];
  return tuple(
    cin,
    () => Number(cin()),
    () => BigInt(cin())
  );
})();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const max = <T extends number | bigint>(...ts: T[]) =>
  ts.reduce((acc, t) => (acc >= t ? acc : t));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const min = <T extends number | bigint>(...ts: T[]) =>
  ts.reduce((acc, t) => (acc <= t ? acc : t));

  
type Color = "R" | "W";

// 1. R...R
// 2. W...W
// 3. R...RW...W
const getAnswer = (N: number, cs: Color[]): number => {
  const rNum = cs.filter((c) => c === "R").length;

  return max(
    rNum,
    N - rNum,
    cs.slice(0, rNum).filter((c) => c === "W").length,
  );
};

{
  const N = nCin();
  const cs = cin()
    .split("")
    .map((c) => c as Color);
  const ans = getAnswer(N, cs);
  console.log(ans);
}
//  [typescript]
{
  const run = (input: string) => {
    let split = input.trim().split("\n")
    const n: number = parseInt(split[0])
    const stones: string[] = split[1].split("")

    let count = 0
    let hasRed = false
    for (let i = 1; i <= n; i++) {
      if (stones[n - i] === 'R') {
        let hasChanged = false
        for (let j = 0; j <= n - i; j++) {
          if (stones[j] === 'W') {
            stones[j] = 'R'
            hasChanged = true
            count++
            break
          }
        }
        if (!hasChanged) hasRed = true;
      } else if (hasRed) {
        count++
      }
    }

    return count
  }

  const Main = (input: string) => {
    console.log(run(input))
  };

  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [typescript]
import { readFileSync } from 'fs'

type Stone = boolean
const WHITE_STONE = false
const RED_STONE = true

const fn = (stones: readonly Stone[]): number => {
  const firstW = stones.indexOf(WHITE_STONE)
  const lastR = stones.lastIndexOf(RED_STONE)

  // 災いを招く石がない場合
  if (firstW === -1 || lastR === -1 || firstW > lastR) {
    return 0
  }

  // 災いを招く石がある場合
  // 入れ替えて再度試す
  const exchanged = stones.map((s, i) => i === firstW || i === lastR ? !s : s)

  return 1 + fn(exchanged)
}

function main(input: string) {
  const [n, stonesStr] = input.split('\n')
  const stones = stonesStr.split('').map(v => v === 'R')

  const res = fn(stones)

  console.log(res)
}


main(readFileSync('/dev/stdin', 'utf8').trim())
//  [python]
n, k = list(map(int, input().split(' ')))
an = list(map(int, input().split(' ')))

check = [-1] * n
i = 0
count = 0
while True:
    if check[i] != -1:
        lsize = count - check[i] 
        tail = count - lsize
        break
    check[i] = count
    count += 1
    i = an[i] - 1

l = k
if k > tail:
    l = ((k - tail) % lsize) + tail

for i in range(n):
    if check[i] == l:
        print(i + 1)
        break
//  [python]
n,k = map(int,input().split())
g = list(map(lambda x: int(x)-1,input().split()))

check = [-1] * n
now = 0
check[now] = 0
cnt = 0
while 1:
    cnt += 1
    now = g[now]
    if check[now] != -1:
        sa = cnt - check[now]
        cnt = cnt + (k - cnt)//sa *sa
        if cnt == k:
                print(now+1)
                exit()
        while 1:
            cnt += 1
            now = g[now]
            if cnt == k:
                print(now+1)
                exit()
    else:
        check[now] = cnt
    if cnt == k:
        print(now+1)
        exit()
//  [python]
n,k=map(int,input().split(" "))
a=[int(i)-1 for i in input().split(" ")]
was=[False]*n
pos=0
while k>0 and not was[pos]:
    was[pos]=True
    pos=a[pos]
    k-=1
if k>0:
    was=[False]*n
    cyc=0
    while not was[pos]:
        was[pos]=True
        pos=a[pos]
        cyc+=1
    k%=cyc
while k>0:
    pos=a[pos]
    k-=1
print(pos+1)
//  [python]
N, K = [int(i) for i in input().split()]
AS = [int(i) for i in input().split()]

visited = set([1])
cnt = 0
t = [1]
p = 1

while AS[p-1] not in visited and cnt < K:
  a = AS[p-1]
  visited.add(a)
  t.append(a)
  p = a
  cnt += 1

if cnt == K:
  print(t[-1])

f_cnt = t.index(AS[p-1])
loop_cnt = cnt + 1 - f_cnt
print(t[f_cnt+(K-f_cnt)%loop_cnt])
//  [python]
import sys
import re
import queue
import collections
import math
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []


def main():
	N,K = i_map()
	A = i_list()

	for i in range(0,len(A)):
		A[i] = A[i] - 1

	lengthA = math.ceil(math.log2(K))

	next = [[0 for _ in range(N)] for _ in range(lengthA)]
	
	for i in range(0,N):
		next[0][i] = A[(i)%(N)]

	for i in range(1,lengthA):
		for j in range(0,N):
			next[i][j] = next[i-1][next[i-1][j]]

	current = 0

	for i in range(0,lengthA):
		if((1 << i) & K):
			current = next[i][current]

	print(current+1)

	return

if __name__ == '__main__':
	main()
//  [python]
n,k=map(int,input().split())
l=list(map(int,input().split()))
cyc=[]
a=1
while a not in cyc:
    cyc.append(a)
    a=l[a-1]
for i in range(len(cyc)):
    if cyc[i]==a:
        leng=len(cyc)-i
        dist=i
        break
if n<=dist-1:
    print(cyc[n])
else:
    print(cyc[(n-dist)%leng+dist])
//  [java]
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		
		int N = stdIn.nextInt();
		long K = stdIn.nextLong();
		ArrayList<Integer> A = new ArrayList<Integer>();
		
		for(int i = 0; i < N; i ++) {
			A.add(stdIn.nextInt() - 1);
		}
		
		ArrayList<Integer> visited = new ArrayList<Integer>();
		ArrayList<Long> when = new ArrayList<Long>();
		for(int i = 0; i < N; i ++) {
			when.add((long) -1);
		}
		
		int now = 0;
		
		visited.add(now);
		when.set(now, K);
		now = A.get(now);
		
		for(long k = K - 1; 0 < k; k --) {
			if(visited.contains(now)) {
				int cycleCnt = (int) (when.get(now) - k);
				k = k % cycleCnt;
				for(int i = 0; i < k; i ++) {
					now = A.get(now);
				}
				break;
			}
			visited.add(now);
			when.set(now, k);
			now = A.get(now);
		}
		
		System.out.println(now + 1);
	}
}
//  [java]
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		
		int N = stdIn.nextInt();
		long K = stdIn.nextLong();
		ArrayList<Integer> A = new ArrayList<Integer>();
		
		for(int i = 0; i < N; i ++) {
			A.add(stdIn.nextInt() - 1);
		}
		
		ArrayList<Integer> visited = new ArrayList<Integer>();
		ArrayList<Long> when = new ArrayList<Long>();
		for(int i = 0; i < N; i ++) {
			when.add((long) -1);
		}
		int now = 0;
		int cnt = 0;
		
		for(long k = K; 0 < k; k --) {
			visited.add(now);
			when.set(now, k);
			now = A.get(now);
			if(visited.contains(now)) {
				int cycleCnt = (int) (when.get(now) - k);
				k = k % cycleCnt;
				for(int i = 1; i < k; i ++) {
					now = A.get(now);
				}
				break;
			}
		}
		
		System.out.println(now + 1);
	}
}
//  [java]
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		
		int N = stdIn.nextInt();
		long K = stdIn.nextLong();
		ArrayList<Integer> A = new ArrayList<Integer>();
		
		for(int i = 0; i < N; i ++) {
			A.add(stdIn.nextInt() - 1);
		}
		
		ArrayList<Integer> visited = new ArrayList<Integer>();
		ArrayList<Long> when = new ArrayList<Long>();
		for(int i = 0; i < N; i ++) {
			when.add((long) -1);
		}
		int now = 0;
		int cnt = 0;
		
		for(long k = K; 0 < k; k --) {
			visited.add(now);
			now = A.get(now);
			if(visited.contains(now)) {
				int cycleCnt = (int) (when.get(now) - k);
				k = k % cycleCnt;
			}
			when.set(now, k);
		}
		
		System.out.println(now + 1);
	}
}
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += 72 - dig >> 3;
	return tmp;
}

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


	ll N = 0, K = 0;
	char c;
	while ((c = getchar_unlocked()) >= '0') N = N * 10 + c - '0';
	while ((c = getchar_unlocked()) >= '0') K = K * 10 + c - '0';

	int A[200001];
	int D2[200001];
	rep1(i, N) A[i] = getint();

	int d = 0;
	int p = 1;
	while (A[p] > 0) {
		D2[d] = p;
		int tugi = A[p];
		A[p] = -d++;
		p = tugi;
	}
	if (K > -A[p]) {
		ll k = K + A[p];
		k %= d + A[p];
		K = -A[p] + k;
	}
	printf("%d", D2[K]);

	Would you please return 0;
}
//  [cpp]
#include<bits/stdc++.h>
//#include <atcoder/all>

#define INF 1e9
#define rep(i,n)for(long long i=0;(i)<(long long)(n);i++)
#define REP(i,a,b)for(long long i=(long long)(a);(i)<=(long long)(b);i++)
#define VEC(type, c, n) std::vector<type> c(n);for(auto& i:c)std::cin>>i;
#define vec(type,n) vector<type>(n)
#define vvec(m,n) vector<vector<int>> (int(m),vector<int>(n))
#define ALL(a)  (a).begin(),(a).end()
#define pb push_back

using namespace std;
//using namespace atcoder;
using ll = long long;
using P = pair<ll, ll>;
//using mint = modint1000000007;


ll cnt[20][20];
int main(){
    ll n, k;
    cin >> n >> k;
    vector<ll> a(n + 1);
    rep(i, n)cin >> a[i];
    int mx = 100;
    vector<vector<ll>> next(mx + 1, vector<ll> (n + 1, -1));
    rep(i, n)next[0][i + 1] = a[i];
    rep(i, mx + 1){
        REP(j, 1, n)next[i + 1][j] = next[i][next[i][j]];
    }
    int now = 1;
    for(int i = mx; i >= 0; i--){
        if(((k >> i) & 1)){
            now = next[i][now];
        }
    }
    cout << now << endl;
  //rep(i, 10){rep(j, n + 1) cout << next[i][j] << " "; cout << endl;}
}
//  [cpp]
#include<bits/stdc++.h>
//#include <atcoder/all>

#define INF 1e9
#define rep(i,n)for(long long i=0;(i)<(long long)(n);i++)
#define REP(i,a,b)for(long long i=(long long)(a);(i)<=(long long)(b);i++)
#define VEC(type, c, n) std::vector<type> c(n);for(auto& i:c)std::cin>>i;
#define vec(type,n) vector<type>(n)
#define vvec(m,n) vector<vector<int>> (int(m),vector<int>(n))
#define ALL(a)  (a).begin(),(a).end()
#define pb push_back

using namespace std;
//using namespace atcoder;
using ll = long long;
using P = pair<ll, ll>;
//using mint = modint1000000007;


ll cnt[20][20];
int main(){
    ll n, k;
    cin >> n >> k;
    vector<ll> a(n + 1);
    rep(i, n)cin >> a[i];
    vector<vector<ll>> next(51, vector<ll> (n + 1, -1));
    rep(i, n)next[0][i + 1] = a[i];
    rep(i, 50){
        REP(j, 1, n)next[i + 1][j] = next[i][next[i][j]];
    }
    int now = 1;
    for(int i = 50; i >= 0; i--){
        if(((k >> i) & 1)){
            now = next[i][now];
        }
    }
    cout << now << endl;
  //rep(i, 10){rep(j, n + 1) cout << next[i][j] << " "; cout << endl;}
}
//  [cpp]
#include<bits/stdc++.h>
//#include <atcoder/all>

#define INF 1e9
#define rep(i,n)for(long long i=0;(i)<(long long)(n);i++)
#define REP(i,a,b)for(long long i=(long long)(a);(i)<=(long long)(b);i++)
#define VEC(type, c, n) std::vector<type> c(n);for(auto& i:c)std::cin>>i;
#define vec(type,n) vector<type>(n)
#define vvec(m,n) vector<vector<int>> (int(m),vector<int>(n))
#define ALL(a)  (a).begin(),(a).end()
#define pb push_back

using namespace std;
//using namespace atcoder;
using ll = long long;
using P = pair<ll, ll>;
//using mint = modint1000000007;


ll cnt[20][20];
int main(){
    ll n, k;
    cin >> n >> k;
    vector<ll> a(n + 1);
    rep(i, n)cin >> a[i];
    vector<vector<ll>> next(50, vector<ll> (n + 1, -1));
    rep(i, n)next[0][i] = a[i];
    rep(i, 50){
        rep(j, n)next[i + 1][j] = next[i][next[i][j]];
    }
    int now = 1;
    for(int i = 50; i >= 0; i--){
        if(k & 1LL << i){
            now = next[i][now];

        }
    }
    cout << now << endl;
}
//  [c]
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif

uint32_t nextpint(void){ char c=getchar_unlocked(); while(c<'0'||'9'<c) c=getchar_unlocked(); uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar_unlocked(); } return x; }
uint64_t nextplong(void){ char c=getchar_unlocked(); while(c<'0'||'9'<c) c=getchar_unlocked(); uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar_unlocked(); } return x; }

uint32_t a[200001];
uint32_t s[200001];
int main(void){
	uint32_t n=nextpint();
	uint64_t k=nextplong();
	for(uint32_t i=1; i<=n; i++){
		a[i]=nextpint();
	}
	uint32_t now=1;
	for(; k>0; k--){
		now = a[now];
		if(s[now]==0){
			s[now]=k;
		}else{
			uint32_t m=s[now]-k;
			k=(k-1)%m;
			break;
		}
	}
	for(; k>0; k--){
		now = a[now];
	}
	printf("%"PRIu32"\n", now);
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(void){
	long long N,K;
	int *A,*check;
	int i,p,loop,flag;
	char str[10000000],buf[10000000];
 
	fgets(str, sizeof(str), stdin);
	N=strtoll(strtok(str ," "),buf,10);
	K=strtoll(strtok(NULL," "),buf,10);

	A=(int*)calloc(N,sizeof(int));
	check=(int*)calloc(N,sizeof(int));

	fgets(str, sizeof(str), stdin);
	A[0]=atoi(strtok(str," "));
	for(i=1;i<N;i++){
		A[i]=atoi(strtok(NULL," "));
	}
	
	p=1;
	check[p-1]=1;flag=0;
	for(i=0;i<K;i++){
		p=A[p-1];
		if( (check[p-1]!=0) && (flag==0)){
          	loop=i+2-check[p-1];
			K=(K-(i+1))%loop+(i+1);
			flag=1;
		}else{
			check[p-1]=i+2;
		}
	}

	printf("%d\n",p);

	free(A);
	free(check);

	return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int n,i,p=1,t=0;
  int start=0;
	long long int k;
	long long int loop;
	int a[300000]={};
	int *b;
	b=(int*)malloc(sizeof(int)*300000);
	for(i=0;i<220000;i++){
		b[i]=0;
	}
	b[1]=1;
	(void)scanf("%d %lld",&n,&k);
	for(i=1;i<=n;i++){
		(void)scanf("%d",&a[i]);
	}
	for(i=0;i<k;i++){
		p=a[p];
		t++;
		if(b[p]!=0){
			start=p;
			break;
		}
		b[p]+=t;
	}
	k-=t;
	//printf("k is %lld\n",k);
	//printf("t is%d\n",t);
	//printf("start is %d\n",start);
	/*for(i=0;i<k;i++){
		p=a[p];
		b[p]+=1;
	}*/
	loop=t-b[start];
	if(start==1){
		loop++;
	}
	//printf("loop is %lld\n",loop);
	k=k%loop;
	for(i=0;i<k;i++){
		p=a[p];
	}
	printf("%d\n",p);
	free(b);
	return 0;
}
//  [c]
#include <iostream>
#include <vector>

using namespace std;
const int N = 2e5 + 1;
long long k;
int n,a[N];
bool avail[N];
vector <int> V;
int main()
{
    cin >> n >> k;
    for (int i = 1; i <= n; i++) cin >> a[i];
    V.push_back(0);
    int start = 1; bool run = false;
    while (avail[a[start]] == false){
        start = a[start];
        avail[start] = true;
        V.push_back(start);
    }
    V.push_back(a[start]);
    //for (int i = 1; i < V.size(); i++) cout << V[i] << " "; cout << "\n";
    int d , c = V.size() - 2;
    for (int i = 1; i < V.size() - 1; i++)
        if (a[start] == V[i]) d = i;
    //cout << d << " " << c << "\n";
    if (k < d) cout << V[k];
    else{
        k = k - d + 1;
        k = k % (c - d + 1);
        if (k == 0) cout << V[c];
        else cout << V[d + k - 1];
    }
    return 0;
}
//  [c]
#include<iostream>
#include<vector>
using namespace std;
typedef long long li;
#define yn(i) print((i)?"Yes":"No")
#define rep(i,n) for(int i=0;i<(n);i++)
#define df 0
template<class T> void print(const T& t){ cout << t << "\n"; }
template<class T, class... Ts> void print(const T& t, const Ts&... ts) { cout << t; if (sizeof...(ts)) cout << " "; print(ts...); }


int main() {
  int n; li k; cin >>n >>k;
  vector<int> a(n); for(auto& x:a){ cin >>x; x--; }
  vector<int> seen(n);
  seen[0]=1;
  int tmp=a[0],cnt=1;
  while(seen[tmp]==0){
    cnt++;
    seen[tmp]=1;
    tmp=a[tmp];
  }
  int tail=0,tmp2=0;
  while(tmp2!=tmp){
    tail++;
    tmp2=a[tmp2];
  }
  
  if(k<=cnt){
    int ans=0;
    rep(i,k){
      ans=a[ans];
    }
    print(ans+1);
    return 0;
  }
  
  int T=cnt-tail;
  li q=(k-tail)/T,r=(k-tail)%T;
  k=min(k,(li)tail);
  int ans=0;
  rep(i,tail+r){
    ans=a[ans];
  }
  print(ans+1);
}
//  [c]
#include<stdio.h>

#define ElementType long long
#define MAX 200010
#define str "%lld"
#define doubleStr "%lld %lld"

int main()
{
	ElementType N, K;
	ElementType i;
	ElementType count;
	ElementType	A[MAX];

	scanf(doubleStr, &N, &K);

	for (i = 1 ; i <= N ; i++)
	{
		scanf(str, &A[i]);
	}

	for (i = 1, count = 0 ; i != 1  || count == 0 ; count++)
	{
		i = A[i];
	}

	K %= count;

	for (count = 0 ; count < K ; count++)
	{
		i = A[i];
	}

	printf(str, i);

	return 0;
}
//  [javascript]
"use strict";
var input = require("fs").readFileSync("/dev/stdin", "utf8");
var cin = input.trim().split(/ |\n/), cid = 0;

function main() {
    let N = +cin.shift();
    let K = BigInt(cin[0]);
    let A = cin.map(i => +i);
    let visit = [];
    let p = 1;
    let offset = 0;
    let interval = 0;
    let map = Array(N);
    for (let i = 0; i < N; i++) {
        visit.push(p);
        map[p] = 1;
        let next = A[p];
        if (map[next]) {
            offset = visit.indexOf(next);
            interval = visit.length - offset;
            break;
        }
        p = next;
    }
    //  console.log(visit)
    // console.log({interval,offset})
    let ans;
    if (K <= offset) {
        ans = visit[K];
    } else {
        let O = BigInt(offset);
        let I = BigInt(interval);
        ans = visit[O + (K - O) % I];
    }
    console.log(ans);
}
main();
//  [javascript]
function Main(input) {
  input = input.trim().split("\n");
  const NK = input[0].split(" ");
  var N = parseInt(NK[0], 10);
  var K = BigInt(NK[1]);
  var Aarr = input[1].split(" ").map((n) => parseInt(n, 10));
  var now = 1;
  var d = 0;
  if (N > K) {
    for (var i = 0; i < K; i++) {
      now = Aarr[now - 1];
    }
    console.log(now);
    return;
  }

  t = new Array(N).fill(-1);
  t[0] = 0;
  for (var i = 1; i <= N; i++) {
    now = Aarr[now - 1];
    if (t[now - 1] != -1) {
      d = i - t[now - 1]; //ループ幅
      var sa = i - d + 1; //あまりの部分
      K -= BigInt(sa);
      if ((K %= BigInt(d)) == 0) {
        K = BigInt(d);
      } else {
        K %= BigInt(d);
      }
      K += BigInt(sa);
      break;
    }
    t[now - 1] = i;
  }

  now = 1;
  for (var i = 0; i < BigInt(K); i++) {
    now = Aarr[now - 1];
  }
  console.log(now);
  return;
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";

const main = arg => {
    const input = arg.trim().split("\n");
    const [N, K] = input[0].split(" ").map(BigInt)
    const as = input[1].split(" ").map(n => Number(n));

    let loop = [0]
    let current = 0
    let loopStart = 0
    let visited = {}
    for (let i = 0; i < K; i++) {
        current = as[current] - 1
        if (visited[current]) {
            loopStart = loop.indexOf(current)
            loop = loop.slice(loopStart)
            break
        }
        visited[current] = true
        loop.push(current)
    }
    console.log(loop[(K - BigInt(loopStart)) % BigInt(loop.length)] + 1)

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
const main = (input) => {
  input = input.trim().split('\n')

  let [, k] = input[0].split(' ').map(BigInt)
  const cities = input[1].split(' ').map(v => parseInt(v, 10) - 1)

  let size = null
  let loop_size
  let before_loop = null

  for (let arr=[0], his={ 0:1 }, i=0; true;) {
    if (~~his[cities[i]]) {
      before_loop = arr.indexOf(cities[i])
      size = arr.length
      loop_size = size - before_loop
      break
    }

    arr.push(cities[i])
    his[cities[i]] = 1
    i = cities[i]
  }

  // console.log('size', size)
  // console.log('loop_size', loop_size)
  // console.log('before', before_loop)

  let start = 0
  let move = k

  if (size < k) {
    start = before_loop
    k -= BigInt(before_loop)
    move = k % BigInt(loop_size)
  }

  let ans = start
  for (let c=0n; c<move; c++) ans = cities[ans]
  return console.log(move === 0n ? cities[ans] + 1 : ans + 1)
}

process.env.MYTEST
  ? (process.env.MYTEST === 'test' ? test() : main(require('fs').readFileSync('dev/stdin', 'utf8')))
  : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
const main = (input) => {
  input = input.trim().split('\n')

  let [, k] = input[0].split(' ').map(BigInt)
  const cities = input[1].split(' ').map(v => parseInt(v, 10) - 1)

  let loop_size = null
  let before_loop = null

  for (let arr=[0], his={ 0:1 }, i=0; true;) {
    if (~~his[cities[i]]) {
      before_loop = arr.indexOf(cities[i])
      loop_size = arr.length
      break
    }

    arr.push(cities[i])
    his[cities[i]] = 1
    i = cities[i]
  }

  let start = 0
  let move = k

  if (loop_size < k) {
    start = before_loop
    k -= BigInt(before_loop)
    if (k < 0n) ppp[11]
    move = k % BigInt(loop_size)
  }

  let ans = start
  for (let c=0n; c<move; c++) ans = cities[ans]


  return console.log(ans + 1)
}

process.env.MYTEST
  ? (process.env.MYTEST === 'test' ? test() : main(require('fs').readFileSync('dev/stdin', 'utf8')))
  : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
const main = (input) => {
  input = input.trim().split('\n')

  let [, k] = input[0].split(' ').map(BigInt)
  const cities = input[1].split(' ').map(v => parseInt(v, 10) - 1)

  let loop_size = null
  let before_loop = null

  for (let arr=[0], his={ 0:1 }, i=0; true;) {
    if (~~his[cities[i]]) {
      before_loop = arr.indexOf(cities[i])
      loop_size = arr.length
      break
    }

    arr.push(cities[i])
    his[cities[i]] = 1
    i = cities[i]
  }

  let start = 0
  let move = k

  if (loop_size < k) {
    start = before_loop
    k -= BigInt(before_loop)
    move = k % BigInt(loop_size)
  }

  let ans = start
  for (let c=0n; c<move; c++) ans = cities[ans]
  
  return console.log(ans + 1)
}

process.env.MYTEST
  ? (process.env.MYTEST === 'test' ? test() : main(require('fs').readFileSync('dev/stdin', 'utf8')))
  : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [go]
package main
import (
  "bufio"
  "os"
  "strconv"
  "strings"
  "fmt"
)

func Solve() {
  var N, K int
  NextInt(&N, &K)
  var A []int
  NextIntVec(&A)
  for i := range A { A[i]-- }
  D := make([]int, N)
  for i := range D { D[i]-- }
  D[0] = 0
  pos, cnt := 0, 0
  for cnt < K {
    pos = A[pos]
    cnt++
    if D[pos] >= 0 { break }
    D[pos] = cnt
  }
  if cnt == K {
    Write(pos + 1)
  } else {
    cnt = D[pos] + (K - cnt) % (cnt - D[pos])
    for i, d := range D {
      if d != cnt { continue }
      Write(i + 1)
    }
  }
}

func main() {
  Solve()
  Output()
}

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)
func NextLine() string {
  buffer := make([]byte, 0)
  for true {
    line, isPrefix, err := reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func NextInt(A ...*int) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.Atoi(L[i])
  }
}
func NextIntVec(A *[]int) {
  L := strings.Split(NextLine(), " ")
  (*A) = make([]int, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.Atoi(l)
  }
}
func NextFloat(A ...*float64) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.ParseFloat(L[i], 64)
  }
}
func NextFloatVec(A *[]float64) {
  L := strings.Split(NextLine(), " ")
  (*A) = make([]float64, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.ParseFloat(l, 64)
  }
}
func Write(s interface{}) {
  fmt.Fprintln(writer, s)
}
func WriteIntVec(A []int) {
  S := make([]string, len(A))
  for i, a := range A {
    S[i] = strconv.Itoa(a)
  }
  Write(strings.Join(S, " "))
}
func Output() {
  _ = writer.Flush()
}
func MaxInt(A ...int) int {
  max := A[0]
  for _, a := range A {
    if max < a { max = a }
  }
  return max
}
func MinInt(A ...int) int {
  min := A[0]
  for _, a := range A {
    if a < min { min = a }
  }
  return min
}
func SumInt(A ...int) int {
  sum := 0
  for _, a := range A {
    sum += a
  }
  return sum
}
func AbsInt(x int) int {
  if x < 0 { x = -x }
  return x
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func Scanner() string {
	sc.Scan()
	return sc.Text()
}

func intScanner() int {
	n, _ := strconv.Atoi(Scanner())
	return n
}

var mod int

func main() {
	mod = 1000000007
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := intScanner()
	k := intScanner()
	as := make([]int, n)
	for i := 0; i < n; i++ {
		as[i] = intScanner() - 1
	}
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = -1
	}
	p[0] = 0
	temp := 0
	for i := 1; ; i++ {
		if k <= n {
			temp = as[temp]
			k--
			if k == 0 {
				fmt.Println(temp + 1)
				break
			}
		} else {
			temp = as[temp]
			if p[temp] == -1 {
				p[temp] = i
				k--
			} else {
				k--
				k %= i - p[temp]
				if k == 0 {
					fmt.Println(temp + 1)
					break
				}
			}
		}
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Code for D - Teleporter
	var N, K int
	fmt.Scan(&N, &K)

	sc.Split(bufio.ScanWords)
	A := make([]int, N)

	for i := 0; i < N; i++ {
		A[i] = nextInt()
	}

	B := make(map[int]int, N)
	B[1]++
	var C int
	for i := 0; i < N; i++ {
		B[A[i]]++
		if B[A[i]] > 1 {
			C = i
			break
		}
	}
	if C == 0 {
		fmt.Println(A[K])
	} else {
		fmt.Println(A[K%C])
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Code for D - Teleporter
	var N, K int
	fmt.Scan(&N, &K)

	sc.Split(bufio.ScanWords)
	A := make([]int, N)

	for i := 0; i < N; i++ {
		A[i] = nextInt()
	}

	B := make(map[int]int, N)
	B[1]++
	var C int
	for i := 0; i < N; i++ {
		B[A[i]]++
		if B[A[i]] > 1 {
			C = i
			break
		}
	}

	fmt.Println(A[K%C])
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

//var warped [250000]int
//var cyc [250000]int

func main() {
	scanInit()

	n := nextInt()

	if n == 1 {
		fmt.Println(1)
		return
	}
	k := nextInt()
	al := make([]int, n+1)
	warped := make([]int, n+1)
	cyc := make([]int, n+1)

	for i := 1; i <= n; i++ {
		al[i] = nextInt()
	}

	now := 1
	warped[1] = 1
	cyc[1] = 1
	cycstartIdx := -1
	cycstartOffset := 1
	clen := 0
	for {
		if cycstartIdx != -1 {
			break
		}

		if warped[al[now]] == 0 {
			cycstartOffset++
			warped[al[now]] = 1
			cyc[cycstartOffset] = al[now]
			now = al[now]
		} else {
			cycstartNum := al[now]
			//fmt.Println("DBG cyc detected cycstartNum=", cycstartNum, " warp=", warped) //! DBG

			for j := 0; j < cycstartOffset; j++ {
				if cyc[j] == cycstartNum {
					cycstartIdx = j
				}
			}
			clen = cycstartOffset - cycstartIdx + 1
			cycstartOffset -= clen
			//fmt.Println("DBG cyc detected cycstartNum=", cycstartNum, " Idx=", cycstartIdx) //! DBG
			//fmt.Println("DBG cyc detected Offset=", cycstartOffset)
			//break //! DBG
		}

	}
	//fmt.Println(cycstartIdx, cycstartOffset, " clen=", clen) //! DBG
	//fmt.Println("DBG: ", warped, cyc)                        //! DBG

	ans := 0
	if k < cycstartOffset {
		ans = cyc[1+k]
	} else {
		ans = cyc[1+cycstartOffset+(k-cycstartOffset)%clen]
	}

	fmt.Println(ans)
}

// ---- readfunc
var sc = bufio.NewScanner(os.Stdin)

func scanInit() {
	const cap = 200 * 1024 // default=64*1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [ruby]
n,k=gets.split.map(&:to_i)
as=gets.split.map(&:to_i)
check=[-1]*n
check[0]=0
i=0
to=0
d=0
while true
  i+=1
  to=as[to]-1
  if i==k
    puts to+1
    exit
  end
  if check[to]>=0
    d=i-check[to]
    break
  else
    check[to]=i
  end
end
m=(k-check[to])%d
puts check.index(check[to]+m)+1
//  [ruby]
nums=gets.strip.split(" ").map do |i|
  i.to_i
end
n=nums[0]
k=nums[1]
s=nums=gets.strip.split(" ").map do |i|
  i.to_i
end
now=1
tele_num=0
a = Array.new(n,nil)
a[0] = 0
flag=false
#puts "tele_num #{tele_num} now #{now}"
while tele_num < k
  next_pos = s[now-1]
  tele_num+=1
  #puts "tele_num #{tele_num} next_pos #{next_pos}"
  if a[next_pos].nil? || flag
    a[next_pos] = tele_num
  else
    #puts "tele_numff #{tele_num}"
    #puts "next_pos #{a[next_pos]}"
    loop_num = tele_num - a[next_pos]
    #puts "loop_num #{loop_num}"
    t=((k - tele_num) / loop_num).to_i 

    tele_num += (t*loop_num)
    flag=true
  end
  now = next_pos
end
puts now
//  [ruby]
n, k = gets.chomp.split(' ').map{|i| i.to_i }
now = 0
count = 0
visited = Array.new(n, false)
visitTime = Array.new(n, -1)
isEnd = false

a = gets.chomp.split(' ').map{|i| i.to_i - 1 }
while !visited[now]
  visited[now] = true
  visitTime[now] = count
  count += 1
  now = a[now]
  if count == k
    isEnd = true
    break
  end
end

if !isEnd
  prefix = visitTime[now]
  loop_count = count - prefix

  rest = k - prefix
  amari = rest % loop_count

  amari.times{|j|
    now = a[now]
  }
end

puts now + 1
//  [ruby]
n, k = gets.split.map(&:to_i)
arr = [0] + gets.split.map(&:to_i)

cur = arr[1]
telep = []
hash = {}
loop_ind = nil
(k + 1).times do
  if !hash[cur].nil?
    loop_ind = hash[cur]
    break
  end
  
  hash[cur] = telep.length
  telep << cur
  cur = arr[cur]
end

if !loop_ind.nil?
  loop_arr = telep[loop_ind..-1]
  kk = (k - telep.length - 1) % loop_arr.length
  cur = loop_arr[kk]
end

puts cur
//  [ruby]
n, k = gets.split.map(&:to_i)
arr = [0] + gets.split.map(&:to_i)

cur = arr[1]
telep = [1]
hash = {1 => 0}
loop_ind = nil
(k + 1).times do
  if !hash[cur].nil?
    loop_ind = hash[cur]
    break
  end
  
  hash[cur] = telep.length
  telep << cur
  cur = arr[cur]
end

if !loop_ind.nil?
  loop_arr = telep[loop_ind..-1]
  kk = (k - telep.length) % loop_arr.length
  cur = loop_arr[kk]
end

puts cur
//  [ruby]
n, k = gets.split.map(&:to_i)
arr = [0] + gets.split.map(&:to_i)

cur = arr[1]
telep = [1]
hash = {1 => 0}
loop_ind = nil
k.times do
  if !hash[cur].nil?
    loop_ind = hash[cur]
    break
  end
  
  hash[cur] = telep.length
  telep << cur
  cur = arr[cur]
end

if !loop_ind.nil?
  loop_arr = telep[loop_ind..-1]
  kk = (k - telep.length) % loop_arr.length
  cur = loop_arr[kk]
end

puts cur
//  [rust]
use std::io::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

    println!("{}", answer);
}

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let n: usize = iterator.next().unwrap().parse().unwrap();
    let k: usize = iterator.next().unwrap().parse().unwrap();
    let a: Vec<usize> = (0..n)
        .map(|_| iterator.next().unwrap().parse().unwrap())
        .collect();

    if k <= n {
        let mut current: usize = 0;
        let mut count: usize = 0;
        while count < k {
            current = a[current] - 1;
            count += 1;
        }

        return (current + 1).to_string();
    }

    let mut current: usize = 0;
    let mut visited: Vec<bool> = vec![false; n];
    let mut route: Vec<usize> = Vec::new();
    loop {
        if visited[current] {
            break;
        }
        route.push(current);
        visited[current] = true;
        current = a[current] - 1;
    }

    let position = route.iter().position(|it| *it == current).unwrap();
    let m = (k - position) % (route.len() - position);
    let ans = route[position + m];
    return (ans + 1).to_string();
}
//  [rust]
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;

fn main() {
    input! {
        n: usize,
        k: u64,
        a: [Usize1; n],
    };

    let mut ci: usize = 0;
    let mut v = vec![std::usize::MAX; n];
    let mut count: usize = 0;
    v[0] = 0;

    for i in 0..n{
        ci = a[ci];

        if i as u64 == k - 1{
            println!("{}", ci + 1);
            return;
        }
        if v[ci] != std::usize::MAX{
            count = i+1;
            break;
        }
        v[ci] = i + 1;
    }

    let ll = count - v[ci];
    let si = count - ll;
    let ret_ind = ((k - si as u64) % (ll as u64)) as usize + si;

    for (i, &vv) in v.iter().enumerate(){
        if vv == ret_ind{
            println!("{}", i+1);
        }
    }

}
//  [rust]
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;

fn main() {
    input! {
        n: usize,
        k: i64,
        a: [Usize1; n],
    }
    let mut t = vec![None; n];
    let mut x = 0;
    let mut l = 0;
    while l < k {
        if let Some(t) = t[x] {
            let d = l - t;
            // println!("aa {} {} {}", x + 1, l, d);
            if k - l > d {
                l += (k - l) / d * d + 1;
            } else {
                l += 1;
            }
        } else {
            t[x] = Some(l);
            l += 1;
        }
        if l <= k {
            x = a[x];
        }
        // println!("{:?}", t);
        // println!("{} {}", x + 1, l);
    }
    println!("{}", x + 1);
}
//  [rust]
// -*- coding:utf-8-unix -*-

use proconio::input;
use std::collections::HashMap;

fn main() {
    input! {
        n: usize,
        k: u64,
        a: [u64; n],
    }

    let mut hm = HashMap::new();
    let mut current_town = 0;
    let mut offset = 0;
    let mut cycle = 0;
    hm.insert(current_town, 0);
    // println!("{:?}", a);
    for i in 1..n {
        if i as u64 == k {
            // println!("{}", current_town);
            return;
        }

        // print!("{} ", current_town);
        current_town = a[current_town as usize] - 1;
        // println!("to {}", current_town);
        if hm.contains_key(&current_town) == true {
            // println!("{:?}", hm);
            cycle = (i as u64 - hm.get(&current_town).unwrap()) as u64;
            offset = i as u64 - cycle;
            break;
        }

        hm.insert(current_town, i as u64);
    }

    // println!("offset: {}, cycle: {}", offset, cycle);
    let p = (k - offset) % cycle;
    for (key, value) in &hm {
        if *value == p + offset {
            println!("{}", key + 1);
            return;
        }
    }
}
//  [rust]
use proconio::{input, fastout};

#[fastout]
fn main() {
    input!{
        n: usize,
        k: usize,
        _a: [usize;n],
    }

    let mut a: Vec<usize> = Vec::new();
    for i in 0..n {
        a.push(_a[i]-1);
    }
    let mut init = a[0];
    let mut v = init;
    let mut cnt = 0;
    let mut flag: Vec<bool> = vec![false;n+5];
    let mut pre = 1;
    loop {
        if flag[v]==false {
            flag[v] = true;
        } else {
            init = v;
            break;
        }
        cnt += 1;
        pre = v;
        v = a[v];
        if cnt==k{
            println!("{}", pre+1);
            return;
        }
    }

    let mut cnt1 = 0;
    v = init;
    for i in 0..cnt {
        v = a[v];
        cnt1 += 1;
        if v==init {
            break;
        }
    }

    let r = (k-(cnt-cnt1)) % cnt1;
    v = init;
    for i in 1..cnt+1 {
        pre = v;
        v = a[v];
        if i==r {
            println!("{}", pre+1);
            return;
        }
    }
}
//  [rust]
use proconio::{input, fastout};

#[fastout]
fn main() {
    input!{
        n: usize,
        k: usize,
        _a: [usize;n],
    }

    let mut a: Vec<usize> = Vec::new();
    for i in 0..n {
        a.push(_a[i]-1);
    }
    let mut init = a[0];
    let mut v = init;
    let mut cnt = 0;
    let mut ans = 1;
    let mut flag: Vec<bool> = vec![false;n+5];
    loop {
        if flag[v]==false {
            flag[v] = true;
        } else {
            init = v;
            break;
        }
        cnt += 1;
        v = a[v];
        if cnt==k{
            ans = v+1;
        }
    }

    let mut cnt1 = 0;
    v = init;
    for i in 0..cnt {
        v = a[v];
        cnt1 += 1;
        if v==init {
            break;
        }
    }

    let r = (k-(cnt-cnt1)) % cnt1;
    v = init;
    for i in 1..cnt+1 {
        v = a[v];
        if i==r {
            ans = v+1;
        }
    }
    for i in 0..n {
        if _a[i]==ans {
            println!("{}", i+1);
            break;
        }
    }

}
//  [swift]
func readTwoInts(separator: String.Element = " ") -> (a: Int, b: Int) {
    let ints = readLine()!.split(separator: separator).map { Int($0)! }
    return (a: ints[0], b: ints[1])
}

func readInts(separator: String.Element = " ") -> [Int] {
    return readLine()!.split(separator: separator).map { Int($0)! }
}

func mainD() {
    let (N, K) = readTwoInts()
    let telepoter = readInts()

    var position = 1
    var positions = Set<Int>()
    var iCount = 1

    for i in 1...K {
        let nextPosition = telepoter[position - 1]
        let previousCount = positions.count
        positions.insert(nextPosition)

        if previousCount == positions.count {
            iCount = i
            break
        }

        position = nextPosition
    }

    var roop = Set<Int>()
    var roopPositions: [Int] = []
    for j in (iCount-1)...K {
        let nextPosition = telepoter[position - 1]
        let previousCount = roop.count
        position = nextPosition
        roop.insert(nextPosition)
        roopPositions.append(nextPosition)

        if previousCount == roop.count {
            // 修正
            let cycle = roop.count

            let answerIndex = (K - (iCount - cycle)) % cycle
            print(roopPositions[answerIndex])
            break
        }
    }
}
mainD()
//  [swift]
/// 10
var (_,k) = cin.pair
/// [2, 3, 4, 5, 6, 4]
/// [1, 2, 3, 4, 5, 3]
let A = cin.array.map { $0-1 }
/// []
var seen = [Int]()
/// 0
var current = 0

while true {
    seen.append(current)
    current = A[current]
    k -= 1

    if k == 0 {
        print(current+1)
        exit(0)
    }

    if seen.contains(current) {
        break
    }
}

/// seen: [0, 1, 2, 3, 4, 5]
/// current: 5
/// loop: [4, 5, 3]
/// k: 10 - 5 = 5

let loop = Array(seen[seen.firstIndex(of: current)!..<seen.count])

/// res = 5%3 = 2
/// loop[2] = 3
/// ans: 5 (index: 4)

let ans = loop[k%loop.count]
print(ans+1)


// MARK: #### 以下、ライブラリ ####

import Foundation
#if os(Linux)
    import Glibc
#else
    import Darwin.C
#endif

enum cin {
    // 123
    static var int: Int { Int(readLine()!)! }
    // 12 23
    static var pair: (Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!) }
    // 12 23 34
    static var triple: (Int, Int, Int) { let line = readLine()!.components(separatedBy: " "); return (Int(line[0])!, Int(line[1])!, Int(line[2])!) }
    // AtCoder
    static var str: String { readLine()! }
    // At Coder
    static var arrayStr: [String] { str.components(separatedBy: " ") }
    // 1 2 3 4
    static var array: [Int] { str.components(separatedBy: " ").map { Int($0)! } }
    // 1
    // 2
    // 3
    static func v_array(count: Int) -> [Int] { (0..<count).map { _ in int } }
}

extension Int {
    // 123 -> [1, 2, 3]
    var digits: [Int] { Array(String(self)).map { Int(String($0))! } }
}

extension Array where Element == Int {
    // [2, 1, 3, 2] -> 8
    var sum: Int { self.reduce(0, +) }
    // [2, 1, 3, 2] -> [1, 2, 2, 3]
    var orderBy: [Int] { sorted() }
    // [2, 1, 3, 2] -> [3, 2, 2, 1]
    var orderByDesc: [Int] { sorted(by: { $0 > $1 }) }
    // [2, 1, 3, 2] -> [2, 1, 3]
    var distinct: [Int] { Array(Set(self)) }
}

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

extension String {
    // e.g. cin.line.regex(match: "^(dream|dreamer|erase|eraser)*$")
    func regex(match pattern: String) -> Bool {
        let regex = try! NSRegularExpression(pattern: pattern)
        return regex.firstMatch(in: self, range: NSRange(location: 0, length: self.count)) != nil
    }
    // "ABC"[1] -> "B"
    subscript(i: Int) -> Character {
        get {
            self[index(at: i)]
        }
        set(char) {
            var characters = Array(self)
            characters[i] = char
            self = String(characters)
        }
    }
    func index(at offset: Int) -> String.Index { index(startIndex, offsetBy: offset) }
    // "ABC".swapAt(0, 1) -> "BAC"
    mutating func swapAt(_ index1: Int, _ index2: Int) {
        var characters = Array(self)
        characters.swapAt(index1, index2)
        self = String(characters)
    }
}