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: Runtime Error)

import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.regex.Pattern
import java.util.{ArrayList, Collections, Comparator, List => JList}

import scala.collection.immutable.TreeMap
import scala.math._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

object Main{
  val LS = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LS);
      println(solve(input).trim());
    }
  }

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

//  def solve(input: String): String = {
//    val Array(n, q) = input.split(LINE_SEPARATOR).head.split(" ").map(_.toInt)
//    val a = input.split(LINE_SEPARATOR).tail.take(n).map(_.split(" ").head.toInt)
//    val b = input.split(LINE_SEPARATOR).tail.take(n).map(_.split(" ").tail.head.toInt)
//    val c = input.split(LINE_SEPARATOR).drop(n + 1).map(_.split(" ").head.toInt)
//    val d = input.split(LINE_SEPARATOR).drop(n + 1).map(_.split(" ").tail.head.toInt)
//    val k = 2 * pow(10, 5).toInt
//    val INF = pow(10, 9).toInt + 1
//    val pqMap = (0 until k).map(_ => new mutable.TreeMap[Int, Int]).toArray
//    def add(k: Int, ai: Int): Unit = {
//      val count = pqMap(k).getOrElse(ai, 0)
//      pqMap(k) += ai -> (count + 1)
//    }
//    def delete(k: Int, ai: Int): Unit = {
//      val count = pqMap(k).getOrElse(ai, 0)
//      if (count == 1) pqMap(k) -= ai else pqMap(k) += ai -> (count - 1)
//    }
//    val i2k = (0 until n).map{i =>
//      b(i)
//    }.toArray
//    (0 until n).foreach{i =>
//      add(b(i) - 1, a(i))
//    }
//    val maxList = pqMap.map(pq => if (pq.nonEmpty) pq.last._1 else INF)
//
//    (0 until q).map{j =>
//      add(d(j) - 1, a(c(j) - 1))
//      delete(i2k(c(j) - 1) - 1, a(c(j) - 1))
//      maxList(i2k(c(j) - 1) - 1) =
//        if (pqMap(i2k(c(j) - 1) - 1).nonEmpty) pqMap(i2k(c(j) - 1) - 1).last._1 else INF
//      i2k(c(j) - 1) = d(j)
//      maxList(d(j) - 1) = if (pqMap(d(j) - 1).nonEmpty) pqMap(d(j) - 1).last._1 else INF
//      maxList.min
//    }.mkString(LINE_SEPARATOR)
//  }

  def solve(input: String): String = {
    val n = input.split(LS).head.split(" ").head.toInt
    val k = input.split(LS).head.split(" ").tail.head.toLong
    val a = input.split(LS).tail.head.split(" ").map(_.toInt)
    var b = 0
    val isVisited = (0 until n).map(i => -1).toArray
    var flg = false
    isVisited(0) = 0
    val loop = (1 until n+ 1).foldLeft(List(1)){(list, i) =>
      if (flg) {-1 +: list} else {
        val nextTown = a(list.head - 1)
        if (isVisited(nextTown - 1) != -1) {
          flg = true
          b = isVisited(nextTown - 1)
          -1 +: list
        } else {
          isVisited(nextTown - 1) = i
          nextTown +: list
        }
      }
    }.filterNot(_ == -1).reverse.drop(b - 1)
    val r = loop.size
    loop(((k - b) % r).toInt).toString
  }

  def divideDigits(num: Long, base: Long = 10L): List[Long] = {
    def proc(num: Long, base: Long, flg: Boolean): List[Long] = {
      var flag = flg
      val quotient = num / base
      val remainder = if (num % base == 0) {
        flag = true
        base
      } else if (flag) {
        flag = false
        val temp = num % base - 1
        if (temp == 0) {
          flag = true
          base - 1
        } else temp
      } else {
        flag = flg
        num % base
      }
      quotient match {
        case 0 =>
          if (flag) {
            List.empty
          } else List(remainder)
        case _ => remainder :: proc(quotient, base, flag)
      }
    }

    proc(num, base, false).reverse//.filterNot(_ == 0)
  }


  def medianCalculator(seq: Seq[Long]): Long = {
    //In order if you are not sure that 'seq' is sorted
    val sortedSeq = seq.sortWith(_ < _)

    if (seq.size % 2 == 1) sortedSeq(sortedSeq.size / 2)
    else {
      val (up, down) = sortedSeq.splitAt(seq.size / 2)
      (up.last + down.head) / 2
    }
  }

  def factorize(x: Long): List[Long] = {
    def foo(x: Long, a: Long = 2, list: List[Long] = Nil): List[Long] = a*a > x match {
      case false if x % a == 0 => foo(x / a, a    , a :: list)
      case false               => foo(x    , a + 1, list)
      case true                => x :: list
    }
    foo(x)
  }

  def divisors(n: Int): Vector[Int] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(n % _ == 0).map(_.toInt)
    val reversedList = if (sqrt(n).floor == sqrt(n)) halfList.reverse.tail.map(n/_) else halfList.reverse.map(n/_)
    halfList ++ reversedList
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

  val tests=List(
    """4 5
      |3 2 4 1""".stripMargin -> """4
                                       |
                                     |
                                                |
                             |
                                   |
                                      |""".stripMargin
    ,
    """6 727202214173249351
      |6 5 2 5 3 2""".stripMargin -> """2
                             |""".stripMargin
  )

  def test():String= {
    return tests.map{case (i,o)=>(i.trim(),o.trim())}
      .zipWithIndex.map{
      case ((input,outputExpect),i)=>{
        val output=solve(input).trim();
        s"test${i+1}:"+(if(output==outputExpect){
          "Passed"
        }else{
          s"Failed\nexpect:\n${outputExpect}\noutput:\n${output}"
        })
      }}
      .mkString("\n");
  }



}