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);
}


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())


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);
}


{
  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"));
}


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())


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


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()


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)


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])


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()


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])


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author iavanish
 */
public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DTeleporter solver = new DTeleporter();
        solver.solve(1, in, out);
        out.close();
    }

    static class DTeleporter {

        public void solve(int testNumber, FastReader in, PrintWriter out) {
            int n = in.nextInt();
            long k = in.nextLong();

            int[] a = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                a[i] = in.nextInt();
            }

            boolean[] isVisited = new boolean[n + 1];
            int curr = 1;
            while (!isVisited[curr]) {
                isVisited[curr] = true;
                curr = a[curr];
            }

            int distanceToCurr = 0;
            int temp = 1;
            while (temp != curr) {
                distanceToCurr++;
                temp = a[temp];
            }

            int revisitCurr = 1;
            temp = a[curr];
            while (temp != curr) {
                revisitCurr++;
                temp = a[temp];
            }

            if (k <= distanceToCurr) {
                temp = 1;
                while (k-- > 0) {
                    temp = a[temp];
                }
                out.println(temp);
            } else {
                k -= distanceToCurr;
                k %= revisitCurr;
                temp = curr;
                while (k-- > 0) {
                    temp = a[temp];
                }
                out.println(temp);
            }
        }

    }

    static class FastReader {

        private final int BUFFER_SIZE = 1 << 16;
        private final InputStream inputStream;
        private final byte[] buffer;
        private int bufferPointer;
        private int bytesRead;

        public FastReader() {
            this.inputStream = new DataInputStream(System.in);
            this.buffer = new byte[BUFFER_SIZE];
            this.bufferPointer = bytesRead = 0;
        }

        public FastReader(InputStream inputStream) {
            this.inputStream = inputStream;
            this.buffer = new byte[BUFFER_SIZE];
            this.bufferPointer = bytesRead = 0;
        }

        public FastReader(String fileName) {
            try {
                this.inputStream = new DataInputStream(new FileInputStream(fileName));
                this.buffer = new byte[BUFFER_SIZE];
                this.bufferPointer = bytesRead = 0;
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }

        public int nextInt() {
            int nextInt = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean negative = (c == '-');
            if (negative) {
                c = read();
            }
            do {
                nextInt = nextInt * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (negative) {
                return -nextInt;
            }
            return nextInt;
        }

        public long nextLong() {
            long nextLong = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean negative = (c == '-');
            if (negative) {
                c = read();
            }
            do {
                nextLong = nextLong * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (negative) {
                return -nextLong;
            }
            return nextLong;
        }

        public void fillBuffer() {
            try {
                bytesRead = inputStream.read(buffer, bufferPointer = 0, BUFFER_SIZE);
                if (bytesRead == -1) {
                    buffer[0] = -1;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public byte read() {
            if (bufferPointer == bytesRead) {
                fillBuffer();
            }
            return buffer[bufferPointer++];
        }

    }

}


import java.io.*;
import java.util.*;

public class Main {
	static void solve() {
		int n = ni();
		long k = nl();
		int a[] = na(n);
		for(int i=0;i<n;i++)a[i]--;
		int used[] = new int[n];
		int now = 0;
		int cnt = 0;
		int start = -1, end = -1;
		int endidx = 0;
		while(true) {
			now = a[now];
			cnt ++;
			if(used[now]!=0) {
				start = used[now];
				end = cnt;
				endidx = now;
				break;
			}
			else used[now] = cnt;
		}
		int cycle = end - start;
		if(k >= end) {
			k -= start;
			k %= cycle;
			int t = endidx;
			for(int i=0;i<k;i++) {
				t = a[t];
			}
			out.println(t+1);
		}
		else {
			int t = 0;
			for(int i=0;i<k;i++) {
				t = a[t];
			}
			out.println(t+1);
		}
	}

	//constant
	static final long mod = (long) 1e9 + 7;
	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
	static final int inf = Integer.MAX_VALUE / 2;
	static final long linf = Long.MAX_VALUE / 3;
	static final double dinf = Double.MAX_VALUE / 3;
	static final double eps = 1e-10;
	static final double pi = Math.PI;
	static StringBuilder sb = new StringBuilder();
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	//libraries
	static void reverse(int ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(long ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(double ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(char ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static String getReverse(String s) {
		char c[] = s.toCharArray();
		reverse(c);
		s = String.valueOf(c);
		return s;
	}

	static <T> void reverse(List<T> ls) {
		int sz = ls.size();
		for (int i = 0; i < sz / 2; i++) {
			T t = ls.get(i);
			ls.set(i, ls.get(sz - 1 - i));
			ls.set(sz - 1 - i, t);
		}
	}

	static <T> void reverse(T[] ar) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			T t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void sbnl() {//StringBuilderに改行文字をappendする
		sb.append("\n");
	}

	static int lowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static <T> int lowerBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) >= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int upperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) > 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rupperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) < 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rlowerBound(List<T> ls, T x) {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) <= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static int[] concat(int x, int arr[]) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static int[] concat(int arr[], int x) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static long[] concat(long x, long arr[]) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static long[] concat(long arr[], long x) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static int max(int x, int y) {
		return Math.max(x, y);
	}

	static int min(int x, int y) {
		return Math.min(x, y);
	}

	static int max(int x, int y, int z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static int min(int x, int y, int z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static long max(long x, long y) {
		return Math.max(x, y);
	}

	static long min(long x, long y) {
		return Math.min(x, y);
	}

	static long max(long x, long y, long z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static long min(long x, long y, long z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static double max(double x, double y) {
		return Math.max(x, y);
	}

	static double min(double x, double y) {
		return Math.min(x, y);
	}

	static double max(double x, double y, double z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static double min(double x, double y, double z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static void sort(int[] ar) {
		Arrays.sort(ar);
	}

	static void sort(long[] ar) {
		Arrays.sort(ar);
	}

	static void sort(double[] ar) {
		Arrays.sort(ar);
	}

	static void sort(char[] ar) {
		Arrays.sort(ar);
	}

	static void rsort(int[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(long[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(double[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(char[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void fill(int arr[], int x) {
		Arrays.fill(arr, x);
	}

	static void fill(long arr[], long x) {
		Arrays.fill(arr, x);
	}

	static void fill(boolean arr[], boolean x) {
		Arrays.fill(arr, x);
	}

	static void fill(double arr[], double x) {
		Arrays.fill(arr, x);
	}

	static void fill(int arr[][], int x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(long arr[][], long x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(double arr[][], double x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(boolean arr[][], boolean x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	//MOD culc
	static long plus(long x, long y) {
		long res = (x + y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long sub(long x, long y) {
		long res = (x - y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long mul(long x, long y) {
		long res = (x * y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long div(long x, long y) {
		long res = x * pow(y, mod - 2) % mod;
		return res < 0 ? res + mod : res;
	}

	static long pow(long x, long y) {
		if (y < 0)
			return 0;
		if (y == 0)
			return 1;
		if (y % 2 == 1)
			return (x * pow(x, y - 1)) % mod;
		long root = pow(x, y / 2);
		return root * root % mod;
	}

	public static void main(String[] args) throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		solve();
		out.flush();
	}

	//input
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;

	private static int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private static boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private static int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	@SuppressWarnings("unused")
	private static double nd() {
		return Double.parseDouble(ns());
	}

	@SuppressWarnings("unused")
	private static char nc() {
		return (char) skip();
	}

	private static String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private static char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	@SuppressWarnings("unused")
	private static char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	@SuppressWarnings("unused")
	private static int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	@SuppressWarnings("unused")
	private static long[] nla(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}

	private static int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	@SuppressWarnings("unused")
	private static long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author iavanish
 */
public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DTeleporter solver = new DTeleporter();
        solver.solve(1, in, out);
        out.close();
    }

    static class DTeleporter {

        public void solve(int testNumber, FastReader in, PrintWriter out) {
            int n = in.nextInt();
            long k = in.nextLong();

            int[] a = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                a[i] = in.nextInt();
            }

            boolean[] isVisited = new boolean[n + 1];
            int curr = 1;
            while (!isVisited[curr]) {
                isVisited[curr] = true;
                curr = a[curr];
            }

            int distanceToCurr = 0;
            int temp = 1;
            while (temp != curr) {
                distanceToCurr++;
                temp = a[temp];
            }

            int revisitCurr = 1;
            temp = a[curr];
            while (temp != curr) {
                revisitCurr++;
                temp = a[temp];
            }

            if (k <= distanceToCurr) {
                temp = 1;
                while (k-- > 0) {
                    temp = a[temp];
                }
                out.println(temp);
            } else {
                k -= distanceToCurr;
                k %= revisitCurr;
                temp = curr;
                while (k-- > 0) {
                    temp = a[temp];
                }
                out.println(temp);
            }
        }

    }

    static class FastReader {

        private final int BUFFER_SIZE = 1 << 16;
        private final InputStream inputStream;
        private final byte[] buffer;
        private int bufferPointer;
        private int bytesRead;

        public FastReader() {
            this.inputStream = new DataInputStream(System.in);
            this.buffer = new byte[BUFFER_SIZE];
            this.bufferPointer = bytesRead = 0;
        }

        public FastReader(InputStream inputStream) {
            this.inputStream = inputStream;
            this.buffer = new byte[BUFFER_SIZE];
            this.bufferPointer = bytesRead = 0;
        }

        public FastReader(String fileName) {
            try {
                this.inputStream = new DataInputStream(new FileInputStream(fileName));
                this.buffer = new byte[BUFFER_SIZE];
                this.bufferPointer = bytesRead = 0;
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }

        public int nextInt() {
            int nextInt = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean negative = (c == '-');
            if (negative) {
                c = read();
            }
            do {
                nextInt = nextInt * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (negative) {
                return -nextInt;
            }
            return nextInt;
        }

        public long nextLong() {
            long nextLong = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean negative = (c == '-');
            if (negative) {
                c = read();
            }
            do {
                nextLong = nextLong * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (negative) {
                return -nextLong;
            }
            return nextLong;
        }

        private void fillBuffer() {
            try {
                bytesRead = inputStream.read(buffer, bufferPointer = 0, BUFFER_SIZE);
                if (bytesRead == -1) {
                    buffer[0] = -1;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private byte read() {
            if (bufferPointer == bytesRead) {
                fillBuffer();
            }
            return buffer[bufferPointer++];
        }

    }

}


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);
	}
}


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);
	}
}


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);
	}
}


#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;
}


#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;}
}


#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;}
}


#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;
}


#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);
}


#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;
}


#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;
}


#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;
}


#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);
}


#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;
}


"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();


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"));


"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'));


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'))


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'))


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'))


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
}


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
				}
			}
		}
	}
}


package main

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

var DEBUG = true

func main() {
	defer Flush()

	N := readi()
	K := readi()
	_, A := readInts(N)
	d := make([]int, N+1)
	for i := range d {
		d[i] = -1
	}
	c := 0
	i := 1
	for ; d[i] == -1; i = A[i-1] {
		d[i] = c
		c++
	}

	e := c - d[i]
	//dbg(c)
	//dbg(d)
	//dbg(e)

	if c <= K {
		K = (K-d[i])%e + d[i]
	}

	for i, v := range d {
		if v == K {
			println(i)
			return
		}
	}

}

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

func dbgf(f string, args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintf(os.Stderr, f, args...)
}

func dbg(args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func minll(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func minf(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func maxll(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

func maxf(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}


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])
	}
}


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])
}


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()
}


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


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


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


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


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


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


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();
}


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);
        }
    }

}


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);
}


// -*- 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;
        }
    }
}


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;
        }
    }
}


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;
        }
    }

}


import Foundation
let main: () = {
    let (N, K) = *listOfInt()
    let A = listOfInt(-1)
    var ans = 0
    var O = IntArray(N) { -1 }
    var S = [Int]()
    var v = 0
    while O[v] == -1 {
        O[v] = S.count
        S.append(v)
        v = A[v]
    }
    let c = S.count - O[v]
    let l = O[v]
    if K < l { return print(S[K] + 1) }
    else {
      var k = K - l
      k %= c
      print(S[l + k] + 1)
    }
}()

//----------------------------------

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

//----------------------------------

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}

extension Array {
    func permutation (_ length: Int) -> [[Element]] {
        if length < 0 || length > self.count {
            return []
        } else if length == 0 {
            return [[]]
        } else {
            var permutations: [[Element]] = []
            let combinations = combination(length)
            for combination in combinations {
                var endArray: [[Element]] = []
                var mutableCombination = combination
                permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray)
            }
            return permutations
        }
    }
    private func permutationHelper(_ n: Int, array: inout [Element], endArray: inout [[Element]]) -> [[Element]] {
        if n == 1 {
            endArray += [array]
        }
        for i in 0  ..< n {
            _ = permutationHelper(n - 1, array: &array, endArray: &endArray)
            let j = n % 2 == 0 ? i : 0
            let temp: Element = array[j]
            array[j] = array[n - 1]
            array[n - 1] = temp
        }
        return endArray
    }
    /**
     - parameter length:
     - returns: Returns all of the combinations in the array of the given length
     */
    func combination (_ length: Int) -> [[Element]] {
        if length < 0 || length > self.count {
            return []
        }
        var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]}
        var combinations: [[Element]] = []
        let offset = self.count - indexes.count
        while true {
            var combination: [Element] = []
            for index in indexes {
                combination.append(self[index])
            }
            combinations.append(combination)
            var i = indexes.count - 1
            while i >= 0 && indexes[i] == i + offset {
                i -= 1
            }
            if i < 0 {
                break
            }
            i += 1
            let start = indexes[i-1] + 1
            for j in (i-1)..<indexes.count {
                indexes[j] = start + j - i + 1
            }
        }
        return combinations
    }
    /**
     - parameter length: The length of each permutations
     - returns: All of the permutations of this array of a given length, allowing repeats
     */
    func repeatedPermutation(_ length: Int) -> [[Element]] {
        if length < 1 {
            return []
        }
        var indexes: [[Int]] = []
        indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes)
        return indexes.map({ $0.map({ i in self[i] }) })
    }
    private func repeatedPermutationHelper(_ seed: [Int], length: Int, arrayLength: Int, indexes: inout [[Int]]) {
        if seed.count == length {
            indexes.append(seed)
            return
        }
        for i in (0..<arrayLength) {
            var newSeed: [Int] = seed
            newSeed.append(i)
            self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes)
        }
    }
}