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

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

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      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 a = input.split(LINE_SEPARATOR).tail.head.split(" ").map(_.toLong)
    val resLog = a.foldLeft(0d)(_ + log10(_))
    val res = a.foldLeft(1L)(_ * _)
    (if ((resLog > 18d || res > pow(10, 18).toLong) && !a.contains(0L)) -1L else res).toString
  }

  def divisors(n: Long): Vector[Long] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(_ % n == 0).map(_.toLong)
    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(
    """2
      |1000000000 1000000000""".stripMargin -> """1000000000000000000
                                                     |
                                                     |
                                                     |
                                                     |
                                        |
                                   |
                                |""".stripMargin,
    """2
      |4294967296 4294967296""".stripMargin -> """-1
                                                 |
                                                 |
                                                 |
                                                 |
                                                 |
                                                 |
                                                 |""".stripMargin,
    """3
      |101 9901 999999000001""".stripMargin -> """-1
                                         |
                               |""".stripMargin,
    """31
      |4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0""".stripMargin -> """0"""
  )

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


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

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

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      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 a = input.split(LINE_SEPARATOR).tail.head.split(" ").map(_.toLong)
    val resLog = a.foldLeft(0d)(_ + log10(_))
    val res = a.foldLeft(1L)(_ * _)
    (if ((resLog > 18d || res > pow(10, 18).toLong) && res != 0) -1L else res).toString
  }

  def divisors(n: Long): Vector[Long] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(_ % n == 0).map(_.toLong)
    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(
    """2
      |1000000000 1000000000""".stripMargin -> """1000000000000000000
                                                     |
                                                     |
                                                     |
                                                     |
                                        |
                                   |
                                |""".stripMargin,
    """3
      |1000000000 1000000000 1000000000""".stripMargin -> """-1
                                                 |
                                                 |
                                                 |
                                                 |
                                                 |
                                                 |
                                                 |""".stripMargin,
    """3
      |101 9901 999999000001""".stripMargin -> """-1
                                         |
                               |""".stripMargin,
    """31
      |4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0""".stripMargin -> """0"""
  )

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

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 200 points

Problem Statement

Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.

However, if the result exceeds 10^{18}, print -1 instead.

Constraints

2 \leq N \leq 10^5

0 \leq A_i \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the value A_1 \times ... \times A_N as an integer, or -1 if the value exceeds 10^{18}.

Sample Input 1

2
1000000000 1000000000

Sample Output 1

1000000000000000000

We have 1000000000 \times 1000000000 = 1000000000000000000.

Sample Input 2

3
101 9901 999999000001

Sample Output 2

-1

We have 101 \times 9901 \times 999999000001 = 1000000000000000001, which exceeds 10^{18}, so we should print -1 instead.

Sample Input 3

31
4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0

Sample Output 3

0

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


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

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

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      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 a = input.split(LINE_SEPARATOR).tail.head.split(" ").map(_.toLong)
    var flag = false
    val res = a.foldLeft(1L){(res, l) =>
      if (log10(res) + log10(l) > 18d) flag = true
      res * l
    }
    (if ((flag || res > pow(10, 18).toLong) && res != 0) -1L else res).toString
  }

  def divisors(n: Long): Vector[Long] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(_ % n == 0).map(_.toLong)
    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(
    """2
      |1000000000 1000000000""".stripMargin -> """1000000000000000000
                                                     |
                                                     |
                                                     |
                                                     |
                                        |
                                   |
                                |""".stripMargin,
    """3
      |101 9901 999999000001""".stripMargin -> """-1
                                         |
                               |""".stripMargin,
    """31
      |4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0""".stripMargin -> """0"""
  )

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


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

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

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      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 n = input.split(LINE_SEPARATOR).head.toLong
    val a = input.split(LINE_SEPARATOR).tail.head.split(" ").map(_.toLong)
    val res = a.foldLeft(0L){_ * _}
    (if (res >= Math.pow(10, 18)) -1L else res).toString
  }

  def divisors(n: Long): Vector[Long] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(_ % n == 0).map(_.toLong)
    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(
    """3 3 10
      |60 2 2 4
      |70 8 7 9
      |50 2 3 9""".stripMargin -> """120
                                        |
                                   |
                                |""".stripMargin,
    """3 3 10
      |100 3 1 4
      |100 1 5 9
      |100 2 6 5""".stripMargin -> """-1
                                         |
                               |""".stripMargin,
    """8 5 22
      |100 3 7 5 3 1
      |164 4 5 2 7 8
      |334 7 2 7 2 9
      |234 4 7 2 8 2
      |541 5 4 3 3 6
      |235 4 8 6 9 7
      |394 3 6 1 6 2
      |872 8 4 3 7 2""".stripMargin -> """1067"""
  )

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


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]
    val as = getArray[Long].sorted

    var product = 1L
    for (a <- as) {
      product *= a
      if ( product > 1000000000000000000L || product < 0L) {
        out.println(-1)
        out.flush()
        return
      }
    }

    out.println(product)
    out.flush()
  }
}


object Main {
  def main(args: Array[String]): Unit ={
    import java.io.{
      BufferedReader,
      InputStreamReader,
    }
    val in = new BufferedReader(new InputStreamReader(System.in))

    val N = in.readLine().toLong;
    val InputArray = in.readLine().split(" ").map(x => BigDecimal(x));
    var answer = BigDecimal("1");

    if (InputArray.contains(0)) {
      println(0);
      return
    }

    for (i <- InputArray) {
      answer *= i;
    }

    if (answer > 1000000000000000000L) {
      println(-1);
      return;
    }

    println(answer);
  }
}


object Main {
  def main(args: Array[String]): Unit ={
    import java.io.{
      BufferedReader,
      InputStreamReader,
    }
    val in = new BufferedReader(new InputStreamReader(System.in))

    val N = in.readLine().toLong;
    val InputArray = in.readLine().split(" ").map(x => BigDecimal(x));
    var answer = BigDecimal("1");

    for (i <- InputArray) {
      answer *= i;
    }

    if (answer > 1000000000000000000L) {
      println(-1);
      return;
    }

    println(answer);
  }
}


object Main {
  def main(args: Array[String]): Unit ={
    import java.io.{
      BufferedOutputStream,
      BufferedReader,
      InputStreamReader,
      PrintWriter
    }
    val in = new BufferedReader(new InputStreamReader(System.in))

    val N = in.readLine().toLong;
    val InputArray = in.readLine().split(" ").map(x => x.toLong);
    var answer = 1L;

    for (i <- InputArray) {
      answer *= i;
    }

    if (answer > 1000000000000000000L) {
      println(-1);
      return;
    }

    println(answer);
  }
}


object Main {
  def main(args: Array[String]): Unit ={
    import java.io.{
      BufferedOutputStream,
      BufferedReader,
      InputStreamReader,
      PrintWriter
    }
    val in = new BufferedReader(new InputStreamReader(System.in))

    val N = in.readLine().toLong;
    val InputArray = in.readLine().split(" ").map(x => x.toLong);
    var answer = 1L;

    for (i <- InputArray) {
      if (i == 0) {
        println(0);
        return;
      }
      answer = answer * i;
    }

    if (answer > 1000000000000000000L) {
      println(-1);
      return;
    }

    println(answer);
    return
  }
}


object Main extends App {
  import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
  val in=new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(new BufferedOutputStream(System.out))
  var ans = 1L
  var flag = false
  var flag2=false
  val n = in.readLine().toInt
  in.readLine().split(" ").map(x => if(x.toLong == 0)flag=true else if(ans * x.toLong > 1E+18 || ans * x.toLong <= 0) flag2=true else ans *= x.toLong)
  out.println(if(flag) 0 else if(flag2) -1 else ans )
  out.flush()
}


object Main extends App {
  import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
  val in=new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(new BufferedOutputStream(System.out))
  var ans = 1L
  var flag = false
  var flag2=false
  val n = in.readLine().toInt
  in.readLine().split(" ").map(x => if(x.toLong == 0)flag=true else if(ans * x.toLong > 1000000000000000000L) flag2=true else ans *= x.toLong)
  out.println(if(flag) 0 else if(flag2) -1 else ans )
  out.flush()
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = BigInt(readInt)
  val as = readLongs

  if (as.contains(0L)) {
    println(0)
  } else {
    var res = BigInt(1)
    val b = new scala.util.control.Breaks
    b.breakable {
      for (a <- as) {
        var temp = res * BigInt(a)
        if (BigInt(pow(10, 18).toLong) < temp) {
          res = BigInt(-1)
          b.break
        } else {
          res = res * a
        }
      }
    }
    println(res)
  }
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import scala.math

object Main extends App {
  val n = io.StdIn.readLine().split(' ')
  val A = (io.StdIn.readLine().split(' ')).map(_.toLong)
  var mult:Long = 1
  for (i <- A){
    mult *= i
    }
  val maxi = math.pow(10,18)
  if (mult >= maxi | mult < 0) println("-1")
  else println(mult)
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  if (as.contains(0L)) {
    println(0)
  } else {
    var res = 1L
    val b = new scala.util.control.Breaks
    b.breakable {
      for (a <- as) {
        var temp = res * a
        if (pow(10, 18).toLong < temp || temp < 0L) {
          res = -1L
          b.break
        } else {
          res = res * a
        }
      }
    }
    println(res)
  }
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import scala.math

object Main extends App {
  val n = io.StdIn.readLine().split(' ')
  val strAry = io.StdIn.readLine().split(' ')
  var mult:Long = 1
  for (i <- strAry){
    mult *= i.toInt
    }
  if (mult > math.pow(10,18)) println("-1")
  else println(mult)
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n = Scanner.nextInt
	var a = 1L

	loop(0, n) { i =>
		val b = Scanner.nextLong
		a = if (b != 0 && a > 1000000000000000000L / b) -1 else a * b
	}

	pw.println(if (a >= 0) a else -1)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


import scala.math

object Main extends App {
  val strAry = io.StdIn.readLine().split(' ')
  var mult:Long = 1
  for (i <- strAry){
    mult *= i.toInt
    }
  if (mult > math.pow(10,18)) println("-1")
  else println(mult)
}


object Main extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine()
  var result = 1L
  val max = 1000000000000000000L
  a.split(" ").map(_.toLong).sorted.foreach { n =>
    if (result != 0L && result != -1L) {
      if (result.toString.length + n.toString.length > 19) {
        result = -1L
      } else {
        result = result * n
        // println(result)
        if (result > max) {
          result = -1L
        } else if (result < 0L) {
          result = -1L
        }
      }
    }
  }
  println(result)
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n = Scanner.nextInt
	var a = 1L
	var flag = true

	loop(0, n) { i =>
		a = a * Scanner.nextLong
		flag = a <= 1000000000000000000L
	}

	pw.println(if (flag) a else -1)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n = Scanner.nextInt
	var a = 1L

	loop(0, n) { i =>
		a = a * Scanner.nextLong
		if (a > 1000000000000000000L) a = -1L
	}

	pw.println(if (a < 0) -1 else a)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  var res = 1L
  val b = new scala.util.control.Breaks

  b.breakable {
    for (a <- as) {
      var temp = res * a
      if (pow(10, 18).toLong < temp) {
        res = -1L
        b.break
      } else {
        res = res * a
      }
    }
  }
  if (as.contains(0L)) {
    println(0)
  } else {
    println(res)
  }
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = Vector.fill(n)(BigInt(sc.nextBigInteger()))

    val l = BigInt.apply("1000000000000000000")
    if (a.contains(BigInt(0))) {
      println(0)
    } else if (a.count(_ > l) > 0) {
      println(-1)
    } else {
      println(loop(0, BigInt(1)))
    }

    def loop(i: Int, s: BigInt): BigInt = {
      if (s > l) {
        BigInt(-1)
      } else if (i >= n) {
        s
      } else {
        loop(i + 1, s * a(i.toInt))
      }
    }

  }

}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n = Scanner.nextInt
	var a = 1L

	loop(0, n) { i =>
		a = a * Scanner.nextLong
		if (a >= 100000000000000000L) a = -1L
	}

	pw.println(if (a < 0) -1 else a)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object Main extends App{
    val n = io.StdIn.readInt
    val a = io.StdIn.readLine.split(" ").map(_.toLong)

    val upper  = BigDecimal(10).pow(18)
    val output = BigDecimal(a.product)

    if (upper < output) println(-1) else println(output)
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  var res = 1L
  val b = new scala.util.control.Breaks
  b.breakable {
    for (a <- as) {
      res = res * a
      if (1000000000000000000L < a) {
        res = -1L
        b.break
      }
      if (1000000000000000000L < res) {
        res = -1L
        b.break
      }
    }
  }

  println(res)
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


object Main extends App {
    val n = io.StdIn.readInt
    val a = io.StdIn.readLine.split(" ").map(_.toLong)

    val upper_limit = BigDecimal(10).pow(18)
    val output = BigDecimal(a.product)
    if (output <= upper_limit) println(output) else println(-1)
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n = Scanner.nextInt
	var a = 1L

	loop(0, n) { i =>
		val b = Scanner.nextLong
		a = if (b <= (1000000000000000000L / a)) a * b else -1
	}

	pw.println(if (a < 0) -1 else a)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  var res = 1L
  val b = new scala.util.control.Breaks
  b.breakable {
    for (a <- as) {
      res = res * a
      if (1000000000000000000L < res) {
        res = -1L
        b.break
      }
    }
  }

  println(res)
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]
    val as = getArray[Long]

    if(as.contains(0L)) {
      out.println(0)
      out.flush()
      return
    }

    var product = 1L
    for (i <- as.indices) {
      product *= as(i)
      if (product > 1000000000000000000L || product < 0L) {
        out.println(-1)
        out.flush()
        return
      }
    }

    out.println(product)

    out.flush()
  }
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  val res = as.foldLeft(1L)(_ * _)

  if (100000000000000000L < res) {
    println("-1")
  } else {
    println(res)
  }
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]
    val as = getArray[Long]

    val product = as.map(a => BigInt(a)).foldLeft(BigInt(1))(_*_)

     out.println(
      if(product > 1000000000000000000L) {
        -1
      } else {
        product
      }
    )

    out.flush()
  }
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  val res = as.foldLeft(1L)(_ * _)

  if (pow(10L, 18) < res) {
    println("-1")
  } else {
    println(res)
  }
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val a = sc.nextLong
  val b = sc.nextDouble
  println(Math.floor(a*b).toLong)
}

Score : 300 points

Problem Statement

Compute A \times B, truncate its fractional part, and print the result as an integer.

Constraints

0 \leq A \leq 10^{15}

0 \leq B < 10

A is an integer.

B is a number with two digits after the decimal point.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the answer as an integer.

Sample Input 1

198 1.10

Sample Output 1

217

We have 198 \times 1.10 = 217.8. After truncating the fractional part, we have the answer: 217.

Sample Input 2

1 0.01

Sample Output 2

0

Sample Input 3

1000000000000000 9.99

Sample Output 3

9990000000000000


import scala.io.StdIn.readLine

object Main extends App {

  val Array(a, b) = readLine().split(' ').map { BigDecimal(_) }

  val s = a * b
  println(s.toBigInt)
}


object Main extends App {
  import io.StdIn._
  val Array(a, b) = readLine().split(" ")
  val (x, y) = (a.toLong, b.toDouble)
  val z = (x * (if (y < 1.0) 0L else math.round(y * 100))) / 100
  println(z)
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val A = sc.nextLong
  val B = BigDecimal(sc.next)

  val z = A * B
  println(z.toString.split("\\.")(0))
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val Array(a, b) = readBigDecimals
  println((a * b).setScale(0, scala.math.BigDecimal.RoundingMode.FLOOR))
}

trait StdInHelper {
  def readStrings = readLine.split(" ")
  def readInts = readStrings.map(_.toInt)
  def readLongs = readStrings.map(_.toLong)
  def readDoubles = readStrings.map(_.toDouble)
  def readBigInts = readStrings.map(BigInt.apply(_))
  def readBigDecimals = readStrings.map(BigDecimal.apply(_))
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val ss = readStrings
  val a = BigDecimal(ss(0).toLong)
  val b = BigDecimal(ss(1).toDouble)

  println((a * b).setScale(0, scala.math.BigDecimal.RoundingMode.FLOOR))
}

trait StdInHelper {
  def readStrings = readLine.split(" ")
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
  def readDoubles = readLine.split(" ").map(_.toDouble)
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val ss = readStrings
  val a = ss(0).toLong
  val b = ss(1).toDouble
  println(floor(a / pow(10, 10).toLong * b).toLong * pow(10, 10).toLong)
}

trait StdInHelper {
  def readStrings = readLine.split(" ")
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
  def readDoubles = readLine.split(" ").map(_.toDouble)
}


import java.util.Scanner

import scala.annotation.tailrec
import scala.collection.mutable

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val a = sc.nextLong()
    val b = sc.nextDouble()
    val bb = math.floor(b * 100).toLong
    println(a * bb / 100)
  }

  //region

  def debug(args: Any*): Unit = {
    Console.err.println(args.mkString(" "))
    Console.err.flush()
  }

  def printExecTime(process: => Unit): Unit = {
    val start = System.currentTimeMillis
    process
    debug("処理時間： " + (System.currentTimeMillis - start) + " ミリ秒")
  }

  def bitSearch[T](n: Int, choice: Vector[T]): Vector[Vector[T]] = {
    @tailrec
    def bitSearchLogic(n: Int,
                       choice: Vector[T],
                       acc: Vector[Vector[T]]): Vector[Vector[T]] = {
      if (n == 0) acc
      else {
        val newAcc =
          acc.flatMap(vec => {
            choice.map(c => vec :+ c)
          })
        bitSearchLogic(n - 1, choice, newAcc)
      }
    }

    val firstAcc = choice.map(i => Vector(i))
    bitSearchLogic(n - 1, choice, firstAcc)
  }

  //endregion
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datA_, datB_) = readLine.split(" ")
    val datA = datA_.toLong
    val datB = (datB_.toDouble * 100).toLong

    val border = math.pow(10,8).toLong

    val datAL = datA % border
    val datAU = datA / border
    val datBL = datB % border
    val datBU = datB / border

    val mulLL = datAL * datBL
    val mulUL = datAU * datBL
    val mulLU = datAL * datBU
    val mulUU = datAU * datBU
    //println(mulLL +" "+ mulUL +" "+ mulLU +" "+ mulUU)
    val ans0 = (mulLL % border) / 100
    val cry0 = mulLL / border

    val ans1_ = mulUL + mulLU + cry0
    val ans1 = ans1_ % border
    val cry1 = ans1_ / border

    val ans2 = mulUU + cry1
    //println(ans0 +" "+ ans1 +" "+ ans2)
    val str0 = if ((ans1 == 0) && (ans2 == 0)) ans0.toString else f"$ans0%06d"
    val str1 = if (ans1 == 0) "" else if (ans2 == 0) ans1.toString else f"$ans1%08d"
    val str2 = if (ans2 == 0) "" else ans2.toString

    println(str2 + str1 + str0)
  }
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val ss = readStrings
  val a = ss(0).toLong
  val b = ss(1).toDouble
  println(floor(a * b).toLong)
}

trait StdInHelper {
  def readStrings = readLine.split(" ")
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
  def readDoubles = readLine.split(" ").map(_.toDouble)
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val Array(a, b) = readDoubles
  println(floor(a * b).toLong)
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
  def readDoubles = readLine.split(" ").map(_.toDouble)
}


object Main extends App {
  val ab = scala.io.StdIn.readLine()
  val abArray = ab.split(" ")

  val a = abArray(0).toLong
  val b = (abArray(1).toDouble * 100).toLong

  println(a / 100 * b + a % 100 * b / 100)
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datA_, datB_) = readLine.split(" ")
    val datA = datA_.toLong
    val datB = (datB_.toDouble * 100).toLong

    val ans: Long = (datA * datB) / 100
    println(ans)
  }
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val (a,_b) = get[Long, String]

    val b:Long = _b.replace(".","")

    out.println(a * b / 100)
    out.flush()
  }
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val a, b = BigDecimal(Scanner.next)

	pw.println((a * b).setScale(0, BigDecimal.RoundingMode.FLOOR))
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


import java.util.Scanner

object Main extends App {
  def readALine(c:Int, ac:List[Int]):List[Int] =
    if (c > 0) readALine(c-1, sc.nextInt::ac) else ac.reverse
  def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
    if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val K = sc.nextLong
  val ls = readALine(N, Nil)
//  println(ls)

  def analyze():(Int, Int, Int) = {
    val usedTowns = Array.fill(N+1)(0)

    def iter(pos:Int, order:Int):(Int, Int, Int) = {
      if (usedTowns(pos) > 0) (pos, usedTowns(pos)-1, order - usedTowns(pos))
      else {
        usedTowns.update(pos, order)
        iter(ma(pos), order+1)
      }
    }

    iter(1, 1)
  }

  def move(s:Int, t:Int):Int = if (t == 0) s else move(ma(s), t-1)

  val ma = (0::ls).toArray
  val (pos, lead, loop) = analyze()

  // println(s"pos:$pos  load:$lead  loop:$loop")
  println(move(pos, ((K-lead) % loop).toInt))
}

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


// import scala.io.StdIn._
import java.util.Scanner

object Main extends App {
  def readALine(c:Int):List[Int] = if (c > 0) sc.nextInt::readALine(c-1) else Nil
  def readLines(r:Int, c:Int):List[List[Int]] = if (r > 0) readALine(c)::readLines(r-1, c) else Nil
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val K = sc.nextLong
  val ls = readALine(N)
//  println(ls)

  def analyze():(Int, Int, Int) = {
    def search(x:Int):Option[(Int, Int)] = {
      def iter(y:Int, ac:Int):Int = if (y == x) ac else iter(ma(y), ac+1)

      // print(s"x:$x ")
      // println(used.mkString(","))
      if (usedTowns(x)) Some(iter(1, 0), iter(ma(x), 1)) else None
    }

    def iter(pos:Int):(Int, Int, Int) = {
      search(pos) match {
        case Some((l, r)) => (pos, l, r)
        case None => {
          usedTowns.update(pos, true)
          iter(ma(pos))
        }
      }
    }

    iter(1)
  }

  def move(s:Int, t:Int):Int = if (t == 0) s else move(ma(s), t-1)

  val ma = (0::ls).toArray
  val usedTowns = Array.fill(N+1)(false)
  val (pos, lead, loop) = analyze()

  // println(s"pos:$pos  load:$lead  loop:$loop")
  println(move(pos, ((K-lead) % loop).toInt))
}


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 to n).foldLeft(List(1)){(list, i) =>
      if (i == k) return a(list.head - 1).toString
      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)
    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,
    """3 1
      |2 3 1
      |""".stripMargin -> """2""",
    """2 1
      |1 1
      |""".stripMargin -> """1"""
  )

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

}


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

}


import scala.io.StdIn._

object Main extends App {
  val Array(n, k) = readLine.split(" ").map(_.toLong)
  val destinations = readLine.split(" ").map(_.toInt - 1) // 0 based index

  var v = 0
  var s = Array.empty[Int]
  val ord = Array.fill[Int](n.toInt)(-1)

  while (ord(v) == -1) {
    ord(v) = s.length
    s :+= v
    v = destinations(v)
  }
  val c = s.length - ord(v)
  val l = ord(v)

  val ans = if (k < l) s(l) else s(l + ((k - l) % c).toInt)
  println(ans + 1) // 1 based index
}


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)

  }
}


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val N = sc.nextInt()
    val K = sc.nextLong()
    val A = Array.fill(N)(sc.nextInt() - 1)
    val B: Array[Option[Int]] = Array.fill(N)(None)
    B(0) = Some(0)
    println(recursive(A, K, B) + 1)
  }

  @scala.annotation.tailrec
  def recursive2(A: Array[Int], K: Long, now: Int): Int = {
    if (K == 0) now
    else recursive2(A, K - 1, A(now))
  }

  @scala.annotation.tailrec
  def recursive(A: Array[Int], K: Long, countA: Array[Option[Int]], now: Int = 0, count: Int = 0): Int = {
    if (K == 0) now
    else
      countA(A(now)) match {
        case Some(a) => {
          recursive2(A, K % (count - a + 1), now)
        }
        case None => {
          countA(A(now)) = Some(count + 1)
          recursive(A, K - 1, countA, A(now), count + 1)
        }
      }
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) =>
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  /*
  def getPermutation(begin: Long = 0): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): LazyList[Long] =
    LazyList.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)
*/
  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    solve(sc)
  }
}

/*
object Util {
  def getPermutation(begin: Long = 0): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

  def getPrimeList: LazyList[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: LazyList[Long]): LazyList[Long] =
    LazyList.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

 */

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  private val codeTable: List[(Int, String)] = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

object PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val K = in.nextLong
  val As = Array.fill(N)(in.nextInt - 1)
  val visited = Array.fill(N)(0)

  def teleport(pos: Int, step: Int): Int = {
    val next = As(pos)
    if (step == K) next
    else if (visited(next) == 0) {
      visited(next) = step + 1
      teleport(next, step + 1)
    } else {
      val diff = step + 1 - visited(next)
      val remain = (K - step) % diff
      def find(p: Int, r: Int): Int = if (r == 0) As(p) else find(As(p), r - 1)
      find(pos, remain.toInt)
    }
  }

  println(teleport(0, 1) + 1)
}


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer
import scala.util.control.Breaks
import scala.math.abs

object Main extends App {

  val sc = new Scanner(System.in)
  val n, k = sc.nextInt()
  sc.nextLine()

  val a = sc.nextLine().split(" ").map(_.toInt)

  println(loop(0, 1))

  def loop(count: Int, index: Int): Long = {
    count match {
      case _ if count == k + 1 => a(index - 1)
      case _ => println(index); loop(count + 1, a(index - 1))
    }
  }

}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n = Scanner.nextInt
	val k = Scanner.nextLong
	val a = Array.fill(n)(Scanner.nextInt - 1)

	val l = Array.fill(n)(true)
	var p = 0
	var closed = 0
	while (l(p)) {
		closed += 1
		l(p) = false
		p = a(p)
	}

	var ans = 0
	var branch = 0
	while(ans != p) {
		branch += 1
		ans = a(ans)
	}
	closed -= branch

	loop(0, ((k-branch) % closed).toInt) { _ => ans = a(ans) }

	pw.println(ans+1)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datN, datK) = readLine.split(" ").map(_.toLong)
    val datA = readLine.split(" ").map(_.toInt - 1)
    val sc = datA.map(a => (false, a))

    def detectLoopEnd(hop: Int, cur: Int, vec: Vector[(Boolean, Int)]): (Int, Int) = vec(cur) match {
        case (arrived, _) if(arrived && hop != 0) => (hop, cur)
        case (_, pos) => detectLoopEnd(hop + 1, pos, vec.updated(cur, (true, pos)))
    }
    val (hopLoopEnd, hopLoopPos) = detectLoopEnd(0, 0, sc.toVector.updated(0, (true, datA(0))))
    //println("DEBUG1:" + hopLoopEnd + " " + hopLoopPos)

    def detectLoopStart(hop: Int, cur: Int, dest: Int): Int = {
      if (cur == dest) hop
      else detectLoopStart(hop + 1, datA(cur), dest)
    }
    val hopLoopStart = detectLoopStart(0, 0, hopLoopPos)
    //println("DEBUG2:" + hopLoopStart)

    def traverse(pos: Int, count: Long): Int = {
      if(count == 0) pos
      else traverse(datA(pos), count - 1)
    }
    val ans = traverse(0, datK % (hopLoopEnd - hopLoopStart))
    println(ans + 1)
  }
}


import scala.collection.mutable
import scala.io.StdIn._

object Main extends App {
  val Array(n, k) = readLine.split(" ").map(_.toLong)
  val destinations = ("0 " + readLine).split(" ").map(_.toInt)

  var current = 0
  var jumps = 0
  var found = false
  var ans = 0

  val stepsToVisit = mutable.Map.empty[Int, Int]
  var visitedArr = Array.empty[Int]

  while (!found) {
    current = if (jumps == 0) 1 else destinations(current)

    if (jumps == k) {
      ans = current
      found = true
    } else if (stepsToVisit.contains(current)) {
      val stepsToFirstVisit = stepsToVisit(current)
      val loopLen = jumps - stepsToFirstVisit
      val shortcut = ((k - stepsToFirstVisit) % loopLen).toInt
      ans = visitedArr(stepsToFirstVisit + shortcut)
      found = true
    } else {
      stepsToVisit.put(current, jumps)
      visitedArr :+= current
      jumps += 1
    }
  }

  println(ans)
}


import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)

    val n = sc.nextInt()
    val k = sc.nextLong()
    val as = Vector.fill(n)(sc.nextInt())

    @scala.annotation.tailrec
    def dfs(now: Int,
            set: Set[Int] = Set.empty[Int],
            acc: Vector[Int] = Vector()): Vector[Int] = {
      if (set.contains(now)) acc :+ now
      else {
        dfs(as(now) - 1, set + now, acc :+ now)
      }
    }

    val m = dfs(0)
    val last = m.last
    val l = m.takeWhile(_ != last)
    val s = m.dropWhile(_ != last).init

    val ans = {
      if (k < l.length) {
        l(k.toInt) + 1
      } else {
        if (l.isEmpty) {
          val mm = k % s.length
          val an = if (mm == s.length) 0 else mm
          s(an.toInt) + 1
        } else {
          val more = k - l.length + 1
          val mm = more % s.length

          val mmm =
            if (mm == 0) s.length - 1 else mm - 1

          s(mmm.toInt) + 1
        }
      }
    }

    println(ans)
  }

  //region

  def debug(args: Any*): Unit = {
    Console.err.println(args.mkString(" "))
  }

  def printExecTime(process: => Unit): Unit = {
    val start = System.currentTimeMillis
    process
    debug("処理時間： " + (System.currentTimeMillis - start) + " ミリ秒")
  }

  def bitSearch[T](n: Int, choice: Vector[T]): Vector[Vector[T]] = {
    @tailrec
    def bitSearchLogic(n: Int,
                       choice: Vector[T],
                       acc: Vector[Vector[T]]): Vector[Vector[T]] = {
      if (n == 0) acc
      else {
        val newAcc =
          acc.flatMap(vec => {
            choice.map(c => vec :+ c)
          })
        bitSearchLogic(n - 1, choice, newAcc)
      }
    }

    val firstAcc = choice.map(i => Vector(i))
    bitSearchLogic(n - 1, choice, firstAcc)
  }
  //endregion
}


import scala.collection.mutable
import scala.io.StdIn._

object Main extends App {
  val Array(n, k) = readLine.split(" ").map(_.toLong)
  val destinations = readLine.split(" ").map(_.toInt - 1)

  var current = 0;
  var jumps = 0;
  var found = false
  var ans = Int.MinValue

  val stepsToVisit = mutable.Map.empty[Int, Int]
  var visitedArr = Array.empty[Int]

  while (!found) {
    current = if (jumps == 0) 0 else destinations(current)

    if (jumps == k) {
      ans = current
      found = true
    } else if (stepsToVisit.contains(current)) {
      println(stepsToVisit)
      println(visitedArr.toSeq)
      val stepsToFirstVisit = stepsToVisit(current)
      val loopLen = jumps - stepsToFirstVisit
      val shortcut = ((k - stepsToFirstVisit) % loopLen).toInt
      println(stepsToFirstVisit, loopLen, shortcut)
      ans = visitedArr(stepsToFirstVisit + shortcut)
      found = true
    } else {
      stepsToVisit.put(current, jumps)
      visitedArr :+= current
      jumps += 1
    }
  }

  println(ans + 1)
}


import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)

    val n = sc.nextInt()
    val k = sc.nextLong()
    val as = Vector.fill(n)(sc.nextInt())

    var map = Vector.fill(n)(Vector())

    @scala.annotation.tailrec
    def dfs(now: Int,
            set: Set[Int] = Set.empty[Int],
            acc: Vector[Int] = Vector()): Vector[Int] = {
      if (set.contains(now)) acc :+ now
      else {
        dfs(as(now) - 1, set + now, acc :+ now)
      }
    }

    val m = dfs(0)
    val last = m.last
    val l = m.takeWhile(_ != last)
    val s = m.dropWhile(_ != last).init

    val ans = {
      if (k <= l.length) l(k.toInt) + 1
      else {
        if (l.isEmpty) {
          val mm = k % s.length
          val an = if (mm == s.length) 0 else mm
          s(an.toInt) + 1
        } else {
          val more = k - l.length + 1
          val mm = more % s.length

          val mmm =
            if (mm == 0) s.length else mm - 1

          s(mmm.toInt) + 1
        }
      }
    }

    println(ans)
  }

  //region

  def debug(args: Any*): Unit = {
    Console.err.println(args.mkString(" "))
  }

  def printExecTime(process: => Unit): Unit = {
    val start = System.currentTimeMillis
    process
    debug("処理時間： " + (System.currentTimeMillis - start) + " ミリ秒")
  }

  def bitSearch[T](n: Int, choice: Vector[T]): Vector[Vector[T]] = {
    @tailrec
    def bitSearchLogic(n: Int,
                       choice: Vector[T],
                       acc: Vector[Vector[T]]): Vector[Vector[T]] = {
      if (n == 0) acc
      else {
        val newAcc =
          acc.flatMap(vec => {
            choice.map(c => vec :+ c)
          })
        bitSearchLogic(n - 1, choice, newAcc)
      }
    }

    val firstAcc = choice.map(i => Vector(i))
    bitSearchLogic(n - 1, choice, firstAcc)
  }
  //endregion
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  val K = in.next().toLong
  val A = new Array[Int](N+1)
  for (i <- 1 to N)
    A(i) = in.next().toInt

  //
  val dp = Array.fill[Int](N+1)(-1)
  var now = A(1)
  var cnt = 0
  var vol = -1
  breakable {
    while (true) {
      if (dp(now) == -1) {
        cnt += 1
        dp(now) = cnt
        now = A(now)
      }
      else {
        vol = dp(now) - 1
        break
      }
    }
  }

  if (K < cnt) {
    val k = K
    for (i <- 1 to N) {
      if (dp(i) == k)
        println(i)
    }
  }
  else {
    val m = (cnt-vol)
    var k = (K-cnt) % m
    if (k == 0) k = m
    for (i <- 1 to N) {
      if (dp(i) - vol == k)
        println(i)
    }
  }

}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val A, B, C, D = sc.nextDouble()
  println(if (math.ceil(C / B).toInt <= math.ceil(A / D).toInt) "Yes" else "No")
}

Score : 200 points

Problem Statement

Takahashi and Aoki will have a battle using their monsters.

The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.

The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ...
Here, an attack decreases the opponent's health by the value equal to the attacker's strength.
The monsters keep attacking until the health of one monster becomes 0 or below. The person with the monster whose health becomes 0 or below loses, and the other person wins.

If Takahashi will win, print Yes; if he will lose, print No.

Constraints

1 \leq A,B,C,D \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

If Takahashi will win, print Yes; if he will lose, print No.

Sample Input 1

10 9 10 10

Sample Output 1

No

First, Takahashi's monster attacks Aoki's monster, whose health is now 10-9=1.

Next, Aoki's monster attacks Takahashi's monster, whose health is now 10-10=0.

Takahashi's monster is the first to have 0 or less health, so Takahashi loses.

Sample Input 2

46 4 40 5

Sample Output 2

Yes


import io.StdIn._

object Main extends App {
  val arr       = readLine.split(" ")
  val tHitPoint = arr(0).toInt
  val tAttack   = arr(1).toInt
  val aHitPoint = arr(2).toInt
  val aAttack   = arr(3).toInt

  def process(tHitPointRest: Int, aHitPointRest: Int, isTsTurn: Boolean): Unit = {
    if (isTsTurn) {
      if ((aHitPointRest - tAttack) > 0) process(tHitPointRest, aHitPointRest - tAttack, !isTsTurn)
      else print("Yes")
    } else {
      if ((tHitPointRest - aAttack) > 0) process(tHitPointRest - aAttack, aHitPointRest, !isTsTurn)
      else print("No")
    }
  }

  process(tHitPoint, aHitPoint, true)
}


import java.util.Scanner

import scala.annotation.tailrec
import scala.io.StdIn._

object Main extends App {

  val Array(a,b,c,d) = readLine().split(" ").map(_.toInt)

  def solve() = {
    var tLife = a
    val tAtk = b
    var aLife = c
    val aAtk = d

    var tTurn = true
    while(tLife > 0 && aLife > 0) {
      if(tTurn) aLife -= tAtk
      else tLife -= aAtk
      tTurn = !tTurn
    }
    if(tLife <= 0) "No" else "Yes"
  }

  println(solve())

}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(tHP, tATK, aHP, aATK) = readLine.split(" ").map(_.toInt)

    val tTurn = (aHP / tATK) + (if (aHP % tATK != 0) 1 else 0)
    val aTurn = (tHP / aATK) + (if (tHP % aATK != 0) 1 else 0)

    val ans = (tTurn <= aTurn)
    println(if(ans) "Yes" else "No")
  }
}


object Main extends App{
  val sc = new java.util.Scanner(System.in)
  var a, b, c, d = sc.nextInt()
  var i,j = 0
  while (a>0){
    i+=1
    a=a-d
  }
  while (c>0){
    j+=1
    c=c-b
  }
  printf(if(i>=j) "Yes" else "No")
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)

  val a = sc.nextInt                 // 入力Aを受け付けて、aに格納する
  val b = sc.nextInt                 // 入力Bを受け付けて、bに格納する
  val c = sc.nextInt                 // 入力Cを受け付けて、cに格納する
  val d = sc.nextInt
  //println(((k+a-1)/a)*a)
  val n = (x:Int, y:Int)=>(x+y-1)/y
  val res = if(n(a,d)>=n(c,b))"Yes"else"No"

  println(res)                       // 結果を出力する
}


object Main extends App {
	var Array(a, b, c, d) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	if((a + d - 1)/d < (c + b - 1)/b) println("No")
	else println("Yes")
}


object Main extends App {                                                                                import scala.math.floor
  val sc = new java.util.Scanner (System.in)
  val a = sc.nextInt
  val b = sc.nextInt
  val c = sc.nextInt
  val d = sc.nextInt
  println(if(a/d<=c/b) "Yes" else "No")
}


object Main extends App {                                                                                import scala.math.floor
  val sc = new java.util.Scanner (System.in)
  val a = sc.nextInt
  val b = sc.nextInt
  val c = sc.nextInt
  val d = sc.nextInt
  println(if(floor(a/d)<=floor(c/b)) "Yes" else "No")
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val a, b, c, d = sc.nextInt()
    val aa = if (a % d == 0) a / d else a / d + 1
    val cc = if (c % b == 0) c / b else c / b + 1

    if (aa >= cc) {
      println("Yes")
    } else {
      println("No")
    }
  }
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}

import scala.collection.mutable

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val s = in.readLine().toList.map(_.toInt - '0').reverse
    val MOD = 2019

    val remainders = s.scanLeft((0, 1)) {
      case ((acc, base), c) =>
        ((acc + base * c) % MOD, base * 10 % MOD)
    }.map(_._1)

    val remainderMap = remainders.foldLeft(mutable.HashMap.empty[Int, Long]) {
      case (acc, remainder) =>
        acc.update(remainder, acc.getOrElse(remainder, 0L) + 1L)
        acc
    }

    out.println(
      remainderMap.foldLeft(0L) {
        case (acc, (_, count)) =>
          acc + count * (count - 1) / 2
      }
    )

    out.flush()
  }
}

Score : 400 points

Problem Statement

Given is a string S consisting of digits from 1 through 9.

Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:

Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.

Constraints

1 ≤ |S| ≤ 200000

S is a string consisting of digits from 1 through 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the condition.

Sample Input 1

1817181712114

Sample Output 1

3

Three pairs - (1,5), (5,9), and (9,13) - satisfy the condition.

Sample Input 2

14282668646

Sample Output 2

2

Sample Input 3

2119

Sample Output 3

0

No pairs satisfy the condition.


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val S = sc.nextLine()
  val a = Array.tabulate(S.length)(x => BigInt(S.takeRight(x + 1)).mod(BigInt(2019))) :+ BigInt(0)
  val b = a.groupBy(_.toInt).view.mapValues(_.length).values.map(x => x * (x - 1) / 2).sum

  println(b)
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val S = in.next()
  val N = S.length
  //
  val h = 2019
  var dp = new Array[Int](h)

  var ans = 0L
  for (i <- 1 to N) {
    val nextDp = new Array[Int](h)
    val now = S(i-1).toString.toInt

    nextDp(now) += 1
    for (k <- 0 until h) {
      val n = (k * 10 + now) % h
      nextDp(n) += dp(k)
    }
    ans += nextDp(0)
    dp = nextDp
  }

  println(ans)
}

// object Sub {
//   def print2DimArray[A](mat: Array[Array[A]]): Unit = {
//     mat.foreach(lin => println(lin.toList))
//   }
// }

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val S = in.next()
  val N = S.length
  // val a = new Array[Int](N)
  val h = 2019
  val dp = Array.ofDim[Long](N+1, h)

  for (i <- 1 to N) {
    val now = S(i-1).toString.toInt

    dp(i)(now) += 1
    for (k <- 0 until h) {
      //dp(i)(k) += dp(i-1)(k)
      val n = (k * 10 + now) % h
      // if (n == 0)
      //   println(k)
      dp(i)(n) += dp(i-1)(k) //
    }
  }

  var ans = 0L
  for (i <- 1 to N)
    ans += dp(i)(0)
  println(ans)
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  case class Edge(to: Int, fee: Int, time: Long)

  case class Node(num: Int, time: Long)

  val N, M, _S = in.next().toInt
  val graph = Array.fill[List[Edge]](N+1)(Nil)
  val nodes = new Array[Node](N+1)
  for (i <- 1 to M) {
    val u, v, a, b = in.next().toInt
    val edge =
    graph(u) = Edge(v, a, b) :: graph(u)
    graph(v) = Edge(u, a, b) :: graph(v)
  }
  for (i <- 1 to N) {
    val c, d = in.next().toInt
    nodes(i) = Node(c, d)
  }

  val sMax = 2500
  val S = Math.min(_S, sMax)

  //
  val MAX = Long.MaxValue

  val dist = Array.ofDim[Long](N+1, sMax+1) // from からの距離を格納する
  for (i <- 1 to N; j <- 0 to sMax)
    dist(i)(j) = MAX

  val check = Array.ofDim[Boolean](N+1, sMax+1)  // すでにその頂点からを調べたかのフラグ

  dist(1)(S) = 0

  val pq = new PriorityQueue[(Long, (Int, Int))]  // (-cost, node) queue
  pq.enqueue((-0, (S, 1)))

  // 頂点は v 個あるので、v 周する
  for(_ <- 0 until N * 2500) {
    // 調べ済みでない頂点のうち、最も近い頂点を now に入れる
    var nowNode = -1       // このターンにフォーカスするノード
    var ginka = -1
    var nowTime = -1L

    breakable {
      while(!pq.isEmpty) {
        val (_time, (_ginka, nodeNum)) = pq.dequeue
        nowNode = nodeNum
        ginka = _ginka
        nowTime = -_time
        if(!check(nowNode)(ginka)){  // まだチェックされていないノードだったら決定
          check(nowNode)(ginka) = true
          break
        }
      }
    }

    if (nowNode != -1) {
      val node = nodes(nowNode)
      if (ginka < sMax) {
        val nextTime = nowTime + node.time
        val nextGinka = (ginka + node.num) min sMax
        dist(nowNode)(nextGinka) = dist(nowNode)(nextGinka) min nextTime

        pq.enqueue((-nextTime, (nextGinka, nowNode)))
      }

      // その頂点からたどり着ける頂点の情報を更新する
      for(Edge(nextNode, fee, time) <- graph(nowNode)) {
        val nextTime = nowTime + time
        val nextGinka = ginka - fee

        if(nextGinka >= 0 && nextTime < dist(nextNode)(nextGinka)){  // 既存の通路より近いなら更新
          dist(nextNode)(nextGinka) = nextTime
          pq.enqueue((-nextTime, (nextGinka, nextNode)))
        }
      }
    }
  }

  for (i <- 2 to N) {
    pw.println(dist(i).min)
  }
  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

Score : 500 points

Problem Statement

There are N cities numbered 1 to N, connected by M railroads.

You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.

The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes.
You cannot use gold coins to pay the fare.

There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin.
The transaction takes D_i minutes for each gold coin you give.
You can exchange any number of gold coins at each exchange counter.

For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.

Constraints

2 \leq N \leq 50

N-1 \leq M \leq 100

0 \leq S \leq 10^9

1 \leq A_i \leq 50

1 \leq B_i,C_i,D_i \leq 10^9

1 \leq U_i < V_i \leq N

There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).

Each city t=2,...,N can be reached from City 1 with some number of railroads.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N

Output

For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.

Sample Input 1

3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5

Sample Output 1

2
14

The railway network in this input is shown in the figure below.

In this figure, each city is labeled as follows:

The first line: the ID number i of the city (i for City i)

The second line: C_i / D_i

Similarly, each railroad is labeled as follows:

The first line: the ID number i of the railroad (i for the i-th railroad in input)

The second line: A_i / B_i

You can travel from City 1 to City 2 in 2 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

You can travel from City 1 to City 3 in 14 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 6 minutes.

Use the 1-st railroad to move from City 2 to City 1 in 2 minutes.

Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.

Sample Input 2

4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4

Sample Output 2

5
5
7

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 4 in 7 minutes, as follows:

At the exchange counter in City 1, exchange 2 gold coins for 6 silver coins in 2 minutes.

Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.

Use the 4-th railroad to move from City 3 to City 4 in 1 minutes.

Sample Input 3

6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1

Sample Output 3

1
9003
14606
16510
16576

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 6 in 16576 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 9000 minutes.

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

At the exchange counter in City 3, exchange 8 gold coins for 8 silver coins in 5600 minutes.

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

Use the 3-rd railroad to move from City 2 to City 4 in 1 minute.

At the exchange counter in City 4, exchange 19 gold coins for 19 silver coins in 1900 minutes.

Use the 3-rd railroad to move from City 4 to City 2 in 1 minute.

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

Use the 4-th railroad to move from City 3 to City 5 in 1 minute.

At the exchange counter in City 5, exchange 63 gold coins for 63 silver coins in 63 minutes.

Use the 4-th railroad to move from City 5 to City 3 in 1 minute.

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 5-th railroad to move from City 1 to City 6 in 1 minute.

Sample Input 4

4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7

Sample Output 4

1
3
5

The railway network in this input is shown in the figure below:

Sample Input 5

2 1 0
1 2 1 1
1 1000000000
1 1

Sample Output 5

1000000001

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 2 in 1000000001 minutes, as follows:

At the exchange counter in City 1, exchange 1 gold coin for 1 silver coin in 1000000000 minutes.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.