Problem:
Score: 400 points

Problem Statement

The Kingdom of Takahashi has N towns, numbered 1 through N.

There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.

Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Help the king by writing a program that answers this question.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2

Solution in Scala (2.13.1) (judge verdict: Accepted)

import java.util.Scanner

import scala.collection.mutable


object Main {

  def main(args: Array[String]): Unit = {

    val sc = new Scanner(System.in)

    val n = sc.nextInt() //街の数
    val k = sc.nextLong() //移動回数
    val as = Vector.fill(n)(sc.nextInt()) //街


    val ans = if (n >= k) {
      def l(count: Int, index: Int): Int = {
        count match {
          case _ if count == k => index
          case _ => l(count + 1, as(index - 1))
        }
      }
      l(0, 1)
    } else {

      val store = mutable.Set.empty[Int] //行った街を保存
      val history = mutable.ArrayBuffer.empty[Int] //行った街の順番を記録

      //周期を調べる 行ったところで最初に被った街を返す 被られたとこから被ったとこまでが周期
      def loop(nowTown: Int): Int = {
        if (store.contains(nowTown))
          nowTown
        else {
          store += nowTown
          history += nowTown
          val nextTown = as(nowTown - 1)
          loop(nextTown)
        }
      }

      val last = loop(1)
      val notCyclic = history.takeWhile(_ != last) //周期が始まる前の記録
      val cyclic = history.dropWhile(_ != last) //周期

      val i = (k - notCyclic.length) % cyclic.length
      cyclic(i.toInt)
    }


    println(ans)

  }
}