There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.    Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).

The first line of the input contains integers n and k (1 ≤ n ≤ 1.5·105, 1 ≤ k ≤ n) — the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 100), where hi is the height of the i-th plank of the fence.

Print such integer j that the sum of the heights of planks j, j + 1, ..., j + k - 1 is the minimum possible. If there are multiple such j's, print any of them.

NoteIn the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8.

import scala.math._

object Problem extends App {
  import Scanner._

  val n, k = readInt
  val heights = Array.fill(n)(readInt)
  val sums = Array.ofDim[Int](n - k)

  var sum = 0
  for(i <- 0 until k)
    sum += heights(i)
  var (min, idx) = (sum, 0)
  for(i <- 1 to (n-k)) {
    sum += heights(i+k-1) - heights(i-1)
    if(sum < min) {
      min = sum
      idx = i
    }
  }
  println(idx+1)
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toLong)
  val first = data.take(k).sum
  val res = (k until n).foldLeft(first, first, 0) {
    case((max, soFar, index), i) =>
      val nSoFar = soFar - data(i - k) + data(i)
      if (nSoFar < max)
        (nSoFar, nSoFar, i - k + 1)
      else
        (max, nSoFar, index)
  }
  println(res._3 + 1)
}

object B363 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val input = readInts(n)
    for (i <- 1 until n) {
      input(i) += input(i-1)
    }
    var ret = input(k-1)
    var I = k-1
    for (i <- k until n) {
      if(ret > input(i)-input(i-k)) {
        ret = input(i)-input(i-k)
        I = i
      }
    }
    println(I-k+2)
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

object P363B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // N planks
  // H_i ... hight of the ith plank
  // K consecutive planks to be removed

  def solve(): Long = {
    val N, K = sc.nextInt
    val dp: Array[Long] = Array.fill(N + 1)(0)

    1 to N foreach { i =>
      dp(i) = dp(i - 1) + sc.nextLong
    }

    var min: Long = Long.MaxValue
    var j: Int = 0
    1 to (N - K + 1) foreach { i =>
      val kSum = dp(i + K - 1) - dp(i - 1)
      if (kSum < min) {
        min = kSum
        j = i
      }
    }
    j
  }

  out.println(solve)
  out.close
}

import scala.collection.mutable.ListBuffer

object Main2 {
  def main(args: Array[String]) {
    var ln = readLine()

    val first = ln.split(' ').toList.map(_.toInt).toArray
    ln =  readLine()
    val second = ln.split(' ').toList.map(_.toInt).toArray
    var sum = BigInt(0)
    var minSum = BigInt(0)
    var pos = 0
    for(i <- 0 to first(1)-1) {
      sum += second(i)
    }
    minSum = sum
    for(j <- 1 to first(0) - first(1)){
      sum -= second(j-1)
      sum += second(first(1)+j-1)
      if(sum < minSum ) {
        minSum = sum
        pos = j
      }
    }

    print(pos+1)
  }

}

object Fence extends App {
  val input = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
  val (n :: hole :: Nil) = input.next.toList
  val fence = input.next
  val fencePairs = fence.zip(fence.drop(hole))

  var total = fence.take(hole).sum
  var min = total
  var plank = 1

  (0 until fencePairs.length) foreach { i =>
    val (drop, gain) = fencePairs(i)
    total = total + gain - drop
    if(total < min) {
      min = total
      plank = i + 2
    }
  }

  println(plank)
}

import java.util.Scanner

object FenceApp extends App {
    val scan: Scanner = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val h: Array[Int] = new Array[Int](n)
    for(i <- 0 until n) {
        h(i) = scan.nextInt
    }

    var ans = 0
    var now = 0
    var best = 0x3fffffff
    for((x,i) <- h.view.zipWithIndex) {
        if (i < k) now += x
        else {
            now += x
            now -= h(i - k)
        }
        if (i >= k - 1 && best > now) {
            ans = i
            best = now
        }
    }
    println(ans - k + 2)
}

import java.util.Scanner

object Fence {
	def main(args: Array[String]): Unit = {
		val scan: Scanner = new Scanner(System.in)
		val n = scan.nextInt
		val k = scan.nextInt

		val h: Array[Int] = new Array[Int](n)
		for(i <- 0 until n) {
			h(i) = scan.nextInt
		}

		var ans = 0
		var now = 0
		var best = 0x3fffffff
		for((x,i) <- h.view.zipWithIndex) {
			if (i < k) now += x
			else {
				now += x
				now -= h(i - k)
			}
			if (i >= k - 1 && best > now) {
				ans = i
				best = now
			}
		}
		println(ans - k + 2)
	}
}

import scala.math._

object Problem extends App {
  import Scanner._

  val n, k = readInt
  val heights = Array.fill(n)(readInt)
  val sums = Array.ofDim[Int](n - k)

  var sum = 0
  for(i <- 0 until k)
    sum += heights(i)
  var min = sum
  for(i <- 1 to (n-k)) {
    sum += heights(i+k-1) - heights(i-1)
    if(sum < min)
      min = sum
  }
  println(min)
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toLong)
  val first = data.take(k).sum
  val res = (k + 1 to n - 1).foldLeft(first, first, 1) {
    case((max, soFar, index), i) =>
      val nSoFar = soFar - data(i - k - 1) + data(k)
      if (nSoFar < max)
        (nSoFar, nSoFar, i - k)
      else
        (max, nSoFar, index)
  }
  println(res._3)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toLong)
  val first = data.take(k).sum
  val res = (k + 1 to n - 1).foldLeft(first, first, 0) {
    case((max, soFar, index), i) =>
      val nSoFar = soFar - data(i - k - 1) + data(k)
      if (nSoFar < max)
        (nSoFar, nSoFar, i - k)
      else
        (max, nSoFar, index)
  }
  println(res._3 + 1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toLong)
  val first = data.take(k).sum
  val res = (k + 1 to n - 1).foldLeft(first, first) {
    case((max, soFar), i) =>
      val nSoFar = soFar - data(i - k - 1) + data(k)
      (Math.min(nSoFar, max), nSoFar)
  }
  println(res._1)
}

object B363 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val input = readInts(n)
    for (i <- 1 until n) {
      input(i) += input(i-1)
    }
    var ret = input(k-1)
    var I = 0
    for (i <- k until n) {
      if(ret > input(i)-input(i-k)) {
        ret = input(i)-input(i-k)
        I = i
      }
    }
    println(I-k+2)
  }
}

import scala.collection.mutable.ListBuffer

object Main2 {
  def main(args: Array[String]) {
    var ln = readLine()

    val first = ln.split(' ').toList.map(_.toInt).toArray
    ln =  readLine()
    val second = ln.split(' ').toList.map(_.toInt).toArray
    var sum = BigInt(0)
    var minSum = BigInt(0)
    var pos = 0
    for(i <- 0 to first(1)-1) {
      sum += second(i)
    }
    minSum = sum
    for(j <- 0 to first(0) - first(1)){
      sum -= second(j)
      sum += second(first(1)-1+j)
      if(sum < minSum ) {
        minSum = sum
        pos = j
      }
    }
    print(pos+1)
  }

}

object Fence extends App {
  val input = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
  val (n :: hole :: Nil) = input.next.toList
  val fence = input.next
  val fencePairs = fence.zip(fence.drop(hole))

  var total = fence.take(hole).sum
  var min = total
  var plank = 0

  (0 until fencePairs.length) foreach { i =>
    val (drop, gain) = fencePairs(i)
    total = total + gain - drop
    if(total < min) {
      min = total
      plank = i + 2
    }
  }

  println(plank)
}

object Fence extends App {
  val input = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
  val (n :: hole :: Nil) = input.next.toList
  val fence = input.next
  val fencePairs = fence.zip(fence.drop(hole))

  var total = fence.take(hole).sum
  var min = total
  var plank = 0

  (0 until fencePairs.length) foreach { i =>
    val (drop, gain) = fencePairs(i)
    total = total + gain - drop
    if(total < min) {
      min = total
      plank = i
    }
  }

  println(plank)
}


Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by $$$2$$$, $$$4$$$ or $$$8$$$, and division is only allowed if the number is divisible by the chosen divisor. Formally, if the register contains a positive integer $$$x$$$, in one operation it can be replaced by one of the following:   $$$x \cdot 2$$$  $$$x \cdot 4$$$  $$$x \cdot 8$$$  $$$x / 2$$$, if $$$x$$$ is divisible by $$$2$$$  $$$x / 4$$$, if $$$x$$$ is divisible by $$$4$$$  $$$x / 8$$$, if $$$x$$$ is divisible by $$$8$$$ For example, if $$$x = 6$$$, in one operation it can be replaced by $$$12$$$, $$$24$$$, $$$48$$$ or $$$3$$$. Value $$$6$$$ isn't divisible by $$$4$$$ or $$$8$$$, so there're only four variants of replacement.Now Johnny wonders how many operations he needs to perform if he puts $$$a$$$ in the register and wants to get $$$b$$$ at the end.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains integers $$$a$$$ and $$$b$$$ ($$$1 \leq a, b \leq 10^{18}$$$) — the initial and target value of the variable, respectively.

Output $$$t$$$ lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get $$$b$$$ at the end, then write $$$-1$$$.

NoteIn the first test case, Johnny can reach $$$5$$$ from $$$10$$$ by using the shift to the right by one (i.e. divide by $$$2$$$).In the second test case, Johnny can reach $$$44$$$ from $$$11$$$ by using the shift to the left by two (i.e. multiply by $$$4$$$).In the third test case, it is impossible for Johnny to reach $$$21$$$ from $$$17$$$.In the fourth test case, initial and target values are equal, so Johnny has to do $$$0$$$ operations.In the fifth test case, Johnny can reach $$$3$$$ from $$$96$$$ by using two shifts to the right: one by $$$2$$$, and another by $$$3$$$ (i.e. divide by $$$4$$$ and by $$$8$$$).

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val ab = readLongLine()
      val a = ab.head
      val b = ab.last
      if (a == b) println(0)
      if (a > b) {
        if (a % b != 0) println(-1)
        else {
          val div = a / b
          println(num(div, 0))
        }
      }
      if (a < b) {
        if (b % a != 0) println(-1)
        else {
          val div = b / a
          println(num(div, 0))
        }
      }
    }
    //          println(minNum(List[Boolean](false, false, true)))
  }

  def num(d: Long, acc: Long): Long = {
    if (d % 8 == 0) num(d / 8, acc + 1)
    else if (d % 4 == 0) num(d / 4, acc + 1)
    else if (d % 2 == 0) num(d / 2, acc + 1)
    else if (d == 1) acc else -1
  }

  def calcCost(tree: Array[List[Int]], nodes: Array[List[Int]]): Long = {
    def helper(visited: Array[Boolean], ind: Int, min: Int): (Int, Int, Long) = {
      val neighs = tree(ind).filter(n => !visited(n))
      neighs.foreach(visited(_) = true)
      val ourCost = nodes(ind).head
      val newMin = Math.min(min, ourCost)

      val costs = neighs.map(n => {
        helper(visited, n, newMin)
      }).reduce((one, two) => (one._1 + two._1, one._2 + two._2, one._3 + two._3))

      if (min <= ourCost) costs else {
        val posExchanges = Math.min(costs._1, costs._2)
        (costs._1 - posExchanges, costs._2 - posExchanges, costs._3 + posExchanges * ourCost)
      }
    }

    val visitedArr = Array.ofDim[Boolean](nodes.length + 1)
    visitedArr(1) = true
    helper(visitedArr, 1, Int.MaxValue)._3
  }

  def constructTree(nodes: Array[List[Int]], edges: List[List[Int]]): Array[List[Int]] = {
    val edgesNice = Array.ofDim[List[Int]](nodes.length + 1)
    for (i <- edgesNice.indices)
      edgesNice(i) = List[Int]()

    edges.foreach(edge => {
      edgesNice(edge.head) = edge.last :: edgesNice(edge.head)
      edgesNice(edge.last) = edge.head :: edgesNice(edge.last)
    })

    edgesNice.map(_.toList)
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

  def printArray[T](arr: Array[T]) {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a, b)  = scala.io.StdIn.readLine().split(" ").map(_.toLong.toBinaryString).sortBy(_.length)
    val (alen, blen) = (a.length, b.length)

    val (bl, br) = b.splitAt(alen)

    val ans =
      if (a != bl || br.contains('1')) -1
      else (blen - alen + 2) / 3

    println(ans)
  }
}

object A extends App {
  import java.{util => ju}
  def leftShiftsRequired(from: Long, to: Long, soFar: Long = 0): Long = {
    if (from == to) soFar
    else if (from > to) -1
    else leftShiftsRequired(from << 1, to, soFar + 1)
  }

  val in = new ju.Scanner(System.in)
  (1 to in.nextInt()).foreach { _ =>
    val a = in.nextLong()
    val b = in.nextLong()

    val shifts = leftShiftsRequired(a min b, a max b)
    if (shifts == -1) println(-1) else {
      val threeShifts = shifts / 3
      val remainingAfterThree = shifts % 3
      val twoShifts = remainingAfterThree / 2
      val oneShifts = remainingAfterThree % 2
      println(threeShifts + twoShifts + oneShifts)
    }
  }
}

import scala.io.StdIn.readLine

object A extends App {

  for {_ <- 0 until readLine.toInt} {
    val Seq(a, b) = readLine.split(" ").toSeq.map(_.toLong)
    println(solution(a, b))
  }

  def solution(a0: Long, b0: Long): Long = {
    val a = a0.toBinaryString
    val b = b0.toBinaryString
    if (before0(a) != before0(b)) -1 else {
      val binDiff = math.abs(trailing0(a) - trailing0(b))
      (binDiff + 2) / 3
    }
  }

  def before0(s: String) = s.reverse.dropWhile(_ == '0')
  def trailing0(s: String) = s.reverse.takeWhile(_ == '0').length
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toLong.toBinaryString).sortBy(_.length)

    val i = b.indexOfSlice(a)

    val ans =
      if (i < 0 || b.indexOfSlice(a, i + 1) > 0) -1
      else (b.length - a.length + 2) / 3

    println(ans)
  }
}


Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x = y2.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — the elements of the array. It is guaranteed that at least one element of the array is not a perfect square.

Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.

NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2.

import java.util.Scanner

object R458A {
  def isSquare(x :Int): Boolean = {
    if(x<0) return false
    if(x==0) return true
    for(i <- 1 to (Math.sqrt(x)+1).toInt) {
      if(i*i==x) {
        return true
      }
    }
    return false
  }
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n)
    for(i <- 0 until n) {
      a(i) = sc.nextInt()
    }
    var max = -10000000
    for(i <- 0 until n) {
      if(!isSquare(a(i))) {
        max = Math.max(a(i), max)
      }
    }
    println(max)
  }
}

object PerfectSquare extends App {
  val n = scala.io.StdIn.readLine().toLong
  val as = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def perfectSquare(x: Long) = {
    if (x < 0) {
      false
    } else {
      Math.sqrt(x).isValidInt
    }
  }

  println(as.filterNot(perfectSquare).max)

}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)

  var max = Int.MinValue

  def isSquare(x: Int): Boolean = {
    x >= 0 && {
      val r = Math.sqrt(x).toInt
      r * r == x
    }
  }

  for (a <- as) {
    if (!isSquare(a) && a > max) max = a
  }

  println(max)
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val b = a.filter(i => i < 0 || scala.math.sqrt(i) % 1 != 0)
  println(b.max)
}

object CF917A extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = Seq.fill[Int](n)(sc.nextInt)
  println(a filter (i => {val d = Math.sqrt(i); d - d.intValue != 0}) max)
}

import java.util.Scanner

object R458A {
  def isSquare(x :Int): Boolean = {
    if(x<=0) return false
    for(i <- 1 to (Math.sqrt(x)+1).toInt) {
      if(i*i==x) {
        return true
      }
    }
    return false
  }
  def main(args: Array[String]): Unit = {
    println(Math.sqrt(-1))
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n)
    for(i <- 0 until n) {
      a(i) = sc.nextInt()
    }
    var max = -10000000
    for(i <- 0 until n) {
      if(!isSquare(a(i))) {
        max = Math.max(a(i), max)
      }
    }
    println(max)
  }
}

import java.util.Scanner

object R458A {
  def isSquare(x :Int): Boolean = {
    if(x<=0) return false
    for(i <- 1 to (Math.sqrt(x)+1).toInt) {
      if(i*i==x) {
        return true
      }
    }
    return false
  }
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n)
    for(i <- 0 until n) {
      a(i) = sc.nextInt()
    }
    var max = -10000000
    for(i <- 0 until n) {
      if(!isSquare(a(i))) {
        max = Math.max(a(i), max)
      }
    }
    println(max)
  }
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val b = a.filter(i => i <= 0 || scala.math.sqrt(i) % 1 != 0)
  println(b.max)
}


In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.

The first line of the input contains n (2 ≤ n ≤ 1000) — number of bidders. The second line contains n distinct integer numbers p1, p2, ... pn, separated by single spaces (1 ≤ pi ≤ 10000), where pi stands for the price offered by the i-th bidder.

The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.

import scala.io.StdIn

object SecondPriceAuction_386A {
  // https://codeforces.com/problemset/problem/386/A?locale=ru
  def main(args: Array[String]): Unit = {
    val numOfMembers = StdIn.readInt()
    val prices = StdIn.readLine().split(" ").map(_.toInt)

    var max = prices.head
    var secondPrice = 0
    var maxIdx = 0
    prices.zipWithIndex.foreach { case (x, i) =>
        if (x > max) {
          secondPrice = max
          max = x
          maxIdx = i
        } else if (x > secondPrice && i > 0) {
          secondPrice = x
        }
    }
    println(s"${maxIdx + 1} ${secondPrice}")
  }

}


Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?  Illustration to the first example.

The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 105).

The output should contain n - 1 real numbers x1, x2, ..., xn - 1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0 < x1 < x2 < ... < xn - 1 < h must hold.  Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteDefinition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle.

import java.util.StringTokenizer

object B extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val h = int().toDouble

  val ans = for (i <- 1 until n) yield {
    h * Math.sqrt(i.toDouble / n)
  }

  println(ans.mkString(" "))

}


Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.

The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly. The second line contains n lowercase English letters — string s. The third line contains m lowercase English letters — string t.

In the first line print single integer k — the minimal number of symbols that need to be replaced. In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.

import scala.collection.mutable.ArrayBuffer

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val s, t = readLine

  var min = Int.MaxValue
  var pos = 0

  for (start <- 0 to t.length - s.length) {
    var diff = 0
    for (i <- 0 until s.length) if (s(i) != t(start + i)) diff += 1
    if (diff < min) {
      min = diff
      pos = start
    }
  }

  val res = ArrayBuffer.empty[Int]
  for (i <- 0 until s.length) if (s(i) != t(pos + i)) res += (i + 1)

  println(min)
  println(res.mkString(" "))
}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)

  val s = StdIn.readLine()
  val t = StdIn.readLine()

  var min = Int.MaxValue
  var index = 0

  (0 to (t.size - s.size)).foreach { i =>
    val sum = (0 to (s.size -1)).map { x =>
      if(t(x + i) != s(x)) 1 else 0
    }.sum
    if(sum < min) {
      min = sum
      index = i
    }
  }

  println(min)
  (0 to (s.size -1)).map { x =>
    if(t(x + index) != s(x)) {
      print((x + 1) + " ")
    }
  }

}

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def gcd(a: Int, b: Int): Int =
    if (b == 0) a
    else gcd(b, a % b)

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val s = next.toCharArray
    val t = next.toCharArray
    var min = Int.MaxValue
    var res = new mutable.HashSet[Int]()
    for (i <- 0 to m - n) {
      var diff = 0
      val pos = new mutable.HashSet[Int]()
      for (j <- 0 until n) {
        if (s(j) != t(i + j)) {
          diff += 1
          pos.add(j + 1)
        }
      }
      if (diff < min) {
        min = diff
        res = pos
      }
    }
    out.println(min)
    res.foreach(x => out.print(s"$x "))
    return 0
  }
}

import java.util.Scanner

object test
{
  def main(args: Array[String]): Unit = {
    val s = new Scanner(System.in)
    val n = s.nextInt()
    val m = s.nextInt()
    s.nextLine()
    val str1 = s.nextLine()
    val str2 = s.nextLine()
    var minlist:List[Int]=List()
    var minc=1e8

    for(i<-0 to m-n){
      var c=0
      var chlist:List[Int]=List()
      for(j<-0 to n-1){
        if(str1.charAt(j)!=str2.charAt(i+j)){
          c+=1
          chlist = j::chlist
        }
      }
      if(c<minc){
        minc=c
        minlist=chlist
      }
    }
    println(minlist.length)
    for(ch<-minlist.reverse) printf("%d ",ch+1)
  }
}

object P822B {

  def diff(s1: String, s2: String): Seq[Int] = (s1 zip s2).zipWithIndex.collect{ case (p, i) if p._1 != p._2 => i+1 }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    in.nextLine() // skip first line
    val s = in.nextLine()
    val t = in.nextLine()
    val idxs = (0 to (t.length - s.length)).map(i => diff(s, t.substring(i))).minBy(_.length)
    println(idxs.length)
    println(idxs.mkString(" "))
  }

  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[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(Files.newBufferedReader(path, codec.charSet))
    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None   // reset
      reader.readLine()
    }
    def lineNumber: Int = reader.getLineNumber
    def line(): String = tokenizer().get.nextToken("\n\r")
    def nextString(): String = next()
    def nextChar(): Char = next().ensuring(_.length == 1).head
    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 next: String = tokenizer().get.nextToken()
    override def hasNext: Boolean = tokenizer().nonEmpty
    override def close(): Unit = reader.close()
  }
}

import java.util.Scanner

object test
{
  def main(args: Array[String]): Unit = {
    val s = new Scanner(System.in)
    val n = s.nextInt()
    val m = s.nextInt()
    s.nextLine()
    val str1 = s.nextLine()
    val str2 = s.nextLine()
    var minlist:List[Int]=List()

    for(i<-0 to m-n){
      var chlist:List[Int]=List()
      for(j<-0 to n-1){
        if(str1.charAt(j)!=str2.charAt(i+j)){
          chlist = j::chlist
        }
      }
      if(minlist.length==0 || chlist.length<minlist.length) minlist=chlist
    }
    println(minlist.length)
    for(ch<-minlist.reverse) printf("%d ",ch+1)
  }
}


Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.

The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take. Each of the next n lines contains two positive space-separated integers ai and bi (1 ≤ bi < ai ≤ 109) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.

Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.

NoteIn the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject.

object Main {

  val in =  {
    val lines = scala.io.Source.stdin.getLines
    lines map (_ split ' ') filter (_.nonEmpty) flatten
  }

  def nextInt = in.next.toInt

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

    val N = nextInt
    val vals = Array.fill(N){
      val a, b = nextInt
      (a, b)
    }.sorted

    var best = 0
    for ((a, b) <- vals) {
      if (b >= best) best = b
      else best = a
    }

    println(best)
  }
}

import scala.collection._

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)

  val abs = Array.ofDim[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    abs(i) = (a, b)
  }

  val maxA = abs.map(_._1).max
  val maxB = abs.map(_._2).max

  val sorted = abs.sorted

  var current = 0
  for ((a, b) <- sorted) {
    if (a > current) {
      if (b >= current) current = b
      else current = a
    }
  }

  println(current)
}

import java.util.StringTokenizer

object _479C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => (next.toInt, next.toInt)).sorted.toArray

  def doit(i: Int, pre: Int):Int = {
    if (i == n) pre
    else {
      if (pre <= a(i)._2) doit(i + 1, a(i)._2)
      else doit(i + 1, a(i)._1)
    }
  }

  println(doit(0, -1))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{_ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (a, b)
  }.sorted.foldLeft(0) {
    case(acc, (a, b)) if b < acc =>
      a
    case(acc, (a, b)) =>
      b
  })

}

object C479 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n){readInts(2)}.map(arr => (arr(0), arr(1))).sorted
    var pos = math.min(in(0)._1, in(0)._2)
    for(i <- 1 until n) {
      val min = math.min(in(i)._1, in(i)._2)
      if(min >= pos) {
        pos = min
      } else {
        pos = math.max(in(i)._1, in(i)._2)
      }
    }
    println(pos)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import scala.collection.mutable.ListBuffer

object P479C {
	def convert(a: Array[Int]) : (Int, Int) = (a(0), a(1))

	def choose(last: Int, choices: (Int, Int)) : Int = {
		if (choices._2 >= last) choices._2 else choices._1
	}

	def main(args: Array[String]) {
		val lines = scala.io.Source.stdin.getLines.toList
		val exams = lines.tail.map(_.split(" ").map(_.toInt))
		println(exams.map(convert).sorted.foldLeft(0)(choose))
	}
}

object Exams{
    def main(args : Array[String]){

        var n : Int = readLine.toInt
        var exams : Array[(Int,Int)] = new Array[(Int,Int)](n)
        var lastExam : Int = 0

        for(i <- 0 to n-1){
            exams(i) = (readLine.split(" ").map(_.toInt)) match {case Array(x,y) => (x,y)}
        }

        exams = exams.sortWith((x, y) => {if (x._1 != y._1) x._1 < y._1 else x._2 < y._2} )
        // exams = exams.sortBy(_._1)

        exams.foreach(exam => {lastExam = if ( exam._2 >= lastExam ) exam._2 else exam._1})

        println(lastExam)
    }
}

import scala.collection._

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)

  val abs = Array.ofDim[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    abs(i) = (a, b)
  }

  val maxA = abs.map(_._1).max
  val maxB = abs.map(_._2).max

  if (abs.filter(_._1 == maxA).forall(_._2 >= maxB))
    println(maxB)
  else println(maxA)
}

import scala.collection._

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)

  val abs = Array.ofDim[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    abs(i) = (a, b)
  }

  val maxA = abs.map(_._1).max
  val maxB = abs.map(_._2).max

  val sorted = abs.sortBy(_._1)

  var current = 0
  for ((a, b) <- sorted) {
    if (a > current) {
      if (b >= current) current = b
      else current = a
    }
  }

  println(current)
}

object Exams{
    def main(args : Array[String]){

        var n : Int = readLine.toInt
        var exams : Array[(Int,Int)] = new Array[(Int,Int)](n)
        var lastExam : Int = 0

        for(i <- 0 to n-1){
            exams(i) = (readLine.split(" ").map(_.toInt)) match {case Array(x,y) => (x,y)}
        }

        exams = exams.sortBy(_._1)

        exams.foreach(exam => {lastExam = if ( exam._2 >= lastExam ) exam._2 else exam._1})

        println(lastExam)
    }
}


You have $$$n$$$ chains, the $$$i$$$-th chain consists of $$$c_i$$$ vertices. Vertices in each chain are numbered independently from $$$1$$$ to $$$c_i$$$ along the chain. In other words, the $$$i$$$-th chain is the undirected graph with $$$c_i$$$ vertices and $$$(c_i - 1)$$$ edges connecting the $$$j$$$-th and the $$$(j + 1)$$$-th vertices for each $$$1 \le j < c_i$$$.Now you decided to unite chains in one graph in the following way:   the first chain is skipped;  the $$$1$$$-st vertex of the $$$i$$$-th chain is connected by an edge with the $$$a_i$$$-th vertex of the $$$(i - 1)$$$-th chain;  the last ($$$c_i$$$-th) vertex of the $$$i$$$-th chain is connected by an edge with the $$$b_i$$$-th vertex of the $$$(i - 1)$$$-th chain.   Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph.A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of chains you have. The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$2 \le c_i \le 10^9$$$) — the number of vertices in the corresponding chains. The third line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_1 = -1$$$; $$$1 \le a_i \le c_{i - 1}$$$). The fourth line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$b_1 = -1$$$; $$$1 \le b_i \le c_{i - 1}$$$). Both $$$a_1$$$ and $$$b_1$$$ are equal to $$$-1$$$, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print the length of the longest simple cycle.

NoteIn the first test case, the longest simple cycle is shown below:   We can't increase it with the first chain, since in such case it won't be simple — the vertex $$$2$$$ on the second chain will break simplicity.

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val cs, as, bs = nextLongs(n)
      var max = 0L
      var aPrev, bPrev = -1L
      var current = 0L
      for (i <- 1 until n) {
        val a = as(i)
        val b = bs(i)
        val c = cs(i)
        val sum1 = Math.abs(a - b) + 2 + c - 1
        val sum2 = if (a == b) 0 else current - Math.abs(a - b) + 2 + c -1
        current = Math.max(sum1, sum2)
        if (current > max) max = current
        aPrev = a
        bPrev = b
      }
      if (current > max) max = current

      out.println(max)
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of m pieces of paper in the garland. Calculate what the maximum total area of the pieces of paper in the garland Vasya can get.

The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≤ m ≤ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.

Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.

NoteIn the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.In the second test sample Vasya cannot make a garland at all — he doesn't have a sheet of color z.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val have = in.next().groupBy(i => i).map(i => i._1 -> i._2.length)
  val need = in.next().groupBy(i => i).map(i => i._1 -> i._2.length)
  println(need.keys.foldLeft(0) {
    case(-1, _) => -1
    case(acc, el) if have.get(el).isEmpty => -1
    case(acc, el) if have(el) > need(el) => acc + need(el)
    case(acc, el) => acc + have(el)
  })
}

object tmp extends App {

  import java.io._
  import scala.collection.mutable
  import java.util.StringTokenizer

  class MyScanner(br: BufferedReader) {
    var st = new StringTokenizer("")

    def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))

    private def next() = {

      while (!st.hasMoreElements) {
        st = new StringTokenizer(br.readLine())
      }
      st.nextToken()
    }

    def nextInt() = java.lang.Integer.parseInt(next())

    def nextLong() = java.lang.Long.parseLong(next())

    def nextLine() = br.readLine()
  }

  val sc = new MyScanner(System.in)
  val in = sc.nextLine().foldLeft(mutable.Map[Char, Int]().withDefaultValue(0)) {
    (acc, cur) => {acc(cur) += 1; acc}
  }
  val out = sc.nextLine().foldLeft(mutable.Map[Char, Int]().withDefaultValue(0)) {
    (acc, cur) => {acc(cur) += 1; acc}
  }
  var result = 0
  for (k <- out.keys) {
    if (in(k) >= out(k)) {
      result += out(k)
    } else if (in(k) == 0) {
      println(-1)
      System.exit(0)
    } else {
      result += in(k)
    }
  }
  println(result)
}

object B extends App {
  val a, b = readLine();
  val ct = (s: String, c: Char) => { s.count(_ == c) }
  val ctm = (l: String) => { l map (ct(l, _: Char)) }
  val am = a.zip(ctm(a)).toMap
  val bm = b.zip(ctm(b)).toMap
  var impossible = false;
  var sum = 0;
  for ((k, n) <- bm)
  {
    if (am.contains(k) == false) {
      impossible = true;
    }
    else {
      sum += n min am(k)
    }
  }
  if (impossible) sum = -1;
  println(sum);
}


One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.

The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.

Print a single integer — the maximum length of a repost chain.

5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya

6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF522A extends App {
  import scala.collection.mutable.{HashMap, HashSet}
  import java.util.{Scanner}
  import java.io.{PrintWriter}

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt

    val graph = HashMap[String, HashSet[String]]()
    (1 to n).foreach { i =>
      val toName = nextString.toLowerCase
      val edge = nextString
      val fromName = nextString.toLowerCase
      if (graph.contains(fromName)) {
        graph(fromName) += toName
      } else {
        graph += (fromName -> HashSet(toName))
      }
    }

    def dfs(node: String): Int = {
      if (!graph.contains(node)) 1 else graph(node).map(dfs(_)).max + 1
    }

    out.println(dfs("Polycarp".toLowerCase))
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

import java.io._
import java.util.StringTokenizer

import scala.collection.mutable

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val g = new Array[Array[Boolean]](500)
    val map = new mutable.HashMap[String, Int]()
    for (i <- 0 until n) {
      val name1 = next.toLowerCase
      next
      val name2 = next.toLowerCase
      val a = map.getOrElse(name2, 0)
      val b = map.getOrElse(name1, 0)
      map.put(name1, Math.max(a + 1, b))
    }
    var max = 0
    map.keySet.foreach(key => {
      max = Math.max(max, map.get(key).get)
    })
    out.println(max + 1)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import scala.collection.mutable._

object Reposts {
  def main(args: Array[String]): Unit = {
     val in =scala.io.StdIn
    var n=in.readInt()
    val arr=Array.fill[Int](n+1)(-1)
    arr(0)= -1
    val hm=HashMap[String,Int]()
    hm.put("polycarp",0)
    for(i<-1 to n){
      var name=in.readLine().split(" reposted ")
      hm.put(name(0).toLowerCase(),i)
      val p=hm.get(name(1).toLowerCase()).get
      arr(i)=p
    }
    var chainSize=2
    for(i<- 1 to n){
      var j=i
      var c=1
      while (arr(j)!= -1){
        c+=1
        j=arr(j)
      }
      chainSize=math.max(chainSize,c)
    }
    println(chainSize)
  }
}

import scala.collection.mutable._

object Reposts {
  def main(args: Array[String]): Unit = {
    //Intuition: here post and re-post hold a parent child relation
    val in =scala.io.StdIn
    var n=in.readInt()
    val cs=HashMap[String,Int]()
    cs.put("polycarp",1)
    var chainSize=0
    for(i<-1 to n){
      var name=in.readLine().split(" reposted ")
      val t=cs.get(name(1).toLowerCase()).get+1
      cs.put(name(0).toLowerCase(),t)
      chainSize=math.max(chainSize,t)
    }
    println(chainSize)
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main3 extends App with IOUtils {
  val n = nextInt
  val pairs = (1 to n).map { i =>
    val to = nextToken
    nextToken
    val from = nextToken
    (from.toLowerCase, to.toLowerCase)
  }
  val descendants = pairs.groupBy(_._1).mapValues(_.map(_._2))

  def deepest(handle: String): Int = descendants.get(handle) match {
    case Some(further) => further.map(deepest).max + 1
    case _ => 0
  }

  println(deepest("polycarp") + 1)
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import scala.collection.mutable.Map

object A522 extends App {

  type Graph = Map[String, List[String]]
  val rep = Map[String, List[String]]()
  val n   = readInt

  (1 to n)
    .map(_ => readLine.toLowerCase.split(" "))
    .foreach(x => if(!rep.contains(x(2))) rep(x(2)) = x(0) :: Nil else rep(x(2)) ::= x(0))

  def BFS(startVertex : String, rep : Graph) = {

    def BFS0(v : String, visited : List[(String, Int)], level : Int = 1) : List[(String, Int)] = {
      if(visited.map(_._1).contains(v) || !rep.contains(v))
        visited
      else {
        val neigh = rep(v).filterNot(x => visited.map(_._1).contains(x))
        neigh.foldLeft((v, level) :: visited)((res, v) => BFS0(v, res, level + 1))
      }
    }

    BFS0(startVertex, List()).map(_._2).max
  }

 println(rep.keys.toList.map(x => BFS(x, rep)).max + 1)
}


A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.

The first line contains five integers n, k, a, b, and q (1 ≤ k ≤ n ≤ 200 000, 1 ≤ b < a ≤ 10 000, 1 ≤ q ≤ 200 000) — the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:    1 di ai (1 ≤ di ≤ n, 1 ≤ ai ≤ 10 000), representing an update of ai orders on day di, or  2 pi (1 ≤ pi ≤ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi?  It's guaranteed that the input will contain at least one query of the second type.

For each query of the second type, print a line containing a single integer — the maximum number of orders that the factory can fill over all n days.

NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.

import scala.collection._
import scala.collection.mutable.ArrayBuffer

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  object BIT {

    def query(t: Array[Long], r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(t: Array[Long], l: Int, r: Int) = query(t, r) - query(t, l - 1)

    def update(t: Array[Long], i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Long]): Array[Long] = {
      val t = Array.fill(src.length) { 0L }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val Array(n, k, a, b, q) = readInts(5)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  val demands = Array.fill(n)(0L)
  val onA = BIT(demands)
  val onB = BIT(demands)
  val res = ArrayBuffer.empty[Long]

  var quer = 0
  while (quer < q) {
    val query = readLine.split(" ").map(_.toInt)
    query match {
      case Array(1, _d, x) =>
        val d = _d - 1
        val newDemand = demands(d) + x
        if (demands(d) < a) {
          BIT.update(onA, d, x.toLong min (a.toLong - demands(d)))
        }
        if (demands(d) < b) {
          BIT.update(onB, d, x.toLong min (b - demands(d)))
        }
        demands(d) = newDemand
      case Array(2, _p) =>
        val p0 = _p - 1
        val p1 = p0 + k
        val r1 = BIT.rangeQuery(onB, 0, p0 - 1)
        val r3 = BIT.rangeQuery(onA, p1, n - 1)
        res += r1 + r3
    }
    quer += 1
  }

  println(res.mkString("\n"))
  Console.flush
}

object _635D extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(read: InputReader) = {
    val n, k, a, b, q = read[Int]
    val fixed, broken = new UpdateableFenwickTree(n + 1)
    val demand = Array.ofDim[Int](n + 1)
    var ans = Vector.empty[Int]
    repeat(q) {
      if(read[Int] == 1) {
        val i, d = read[Int]
        demand(i) += d
        fixed(i) = demand(i) min a
        broken(i) = demand(i) min b
      } else {
        val d = read[Int]
        val (r1, r2) = (broken.sum(1, d - 1), fixed.sum(d + k, n))
        ans = ans :+ (r1 + r2)
      }
    }
    ans
  }

  trait BitIndexTree {
    def prefixSum(i: Int): Int
    def sum(start: Int, end: Int): Int = prefixSum(end) - prefixSum(start - 1)
    def +=(i: Int, delta: Int): Unit
  }

  class FenwickTree(n: Int) extends BitIndexTree {
    private[this] val tree = Array.ofDim[Int](n)

    override def prefixSum(i: Int) = if (i < 0) 0 else tree(i) + prefixSum((i & (i + 1)) - 1)

    override def +=(i: Int, delta: Int) = if (i < n) {
      tree(i) += delta
      this += (i | (i + 1), delta)
    }
  }

  class UpdateableFenwickTree(n: Int) extends FenwickTree(n) {
    private[this] val data = Array.ofDim[Int](n)

    def update(i: Int, value: Int) = {
      this += (i, value - data(i))
      data(i) = value
    }
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f

  override def format(result: Result) = result mkString "\n"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

object _635D extends CodeForcesApp {
  override type Result = Seq[Long]

  override def solve(read: InputReader) = {
    val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]
    val (fixed, broken, demand) = (new FenwickTree(n + 1), new FenwickTree(n + 1), Array.ofDim[Long](n))
    var ans = Vector.empty[Long]
    repeat(q) {
      if(read[Int] == 1) {
        val (d, x) = read[(Int, Long)]
        if (demand(d-1) < a) fixed(d-1) = x min (a - demand(d-1))
        if (demand(d-1) < b) broken(d-1) = x min (b - demand(d-1))
        demand(d-1) += x
      } else {
        val d = read[Int]
        val r1 = broken(0, d - 2)
        val r2 = fixed(d + k - 1, n - 1)
        ans = ans :+ (r1 + r2)
      }
    }

    ans
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f

  class FenwickTree(n: Int) {
    private[this] val tree = Array.ofDim[Long](n)

    def apply(i: Int): Long = if (i < 0) 0 else tree(i) + apply((i & (i + 1)) - 1)

    def apply(start: Int, end: Int): Long = this(end) - this(start - 1)

    def update(i: Int, v: Long): Unit = if (i < n) {
      tree(i) += v
      this(i | (i + 1)) = v
    }

    override def toString = tree.indices map apply mkString ", "
  }

  override def format(result: Result) = result mkString "\n"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

object _635D extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(read: InputReader) = {
    val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]
    val fixed, broken = new UpdateableFenwickTree(n + 1)
    val demand = Array.ofDim[Int](n + 1)
    var ans = Vector.empty[Int]
    repeat(q) {
      if(read[Int] == 1) {
        val (i, d) = read[(Int, Int)]
        demand(i) += d
        fixed(i) = demand(i) min a
        broken(i) = demand(i) min b
      } else {
        val d = read[Int]
        val r1 = broken.sum(1, d - 1)
        val r2 = fixed.sum(d + k, n)
        ans = ans :+ (r1 + r2)
      }
    }
    ans
  }

  trait BitIndexTree {
    def prefixSum(i: Int): Int
    def sum(start: Int, end: Int): Int = prefixSum(end) - prefixSum(start - 1)
    def +=(i: Int, delta: Int): Unit
  }

  class FenwickTree(n: Int) extends BitIndexTree {
    private[this] val tree = Array.ofDim[Int](n)

    override def prefixSum(i: Int) = if (i < 0) 0 else tree(i) + prefixSum((i & (i + 1)) - 1)

    override def +=(i: Int, delta: Int) = if (i < n) {
      tree(i) += delta
      this += (i | (i + 1), delta)
    }
  }

  class UpdateableFenwickTree(n: Int) extends FenwickTree(n) {
    private[this] val data = Array.ofDim[Int](n)

    def update(i: Int, value: Int) = {
      this += (i, value - data(i))
      data(i) = value
    }
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f

  override def format(result: Result) = result mkString "\n"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

object _635D extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(read: InputReader) = {
    val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]
    val fixed = new UpdateableFenwickTree(n + 1)
    val broken = new UpdateableFenwickTree(n + 1)
    val demand = Array.ofDim[Int](n + 1)
    var ans = Vector.empty[Int]
    repeat(q) {
      if(read[Int] == 1) {
        val (i, d) = read[(Int, Int)]
        demand(i) += d
        fixed(i) = demand(i) min a
        broken(i) = demand(i) min b
      } else {
        val d = read[Int]
        val r1 = broken(1, d - 1)
        val r2 = fixed(d + k, n)
        ans = ans :+ (r1 + r2)
      }
    }
    ans
  }

  trait BitIndexTree {
    def apply(i: Int): Int
    def apply(start: Int, end: Int): Int = this(end) - this(start - 1)
    def +=(i: Int, delta: Int): Unit
  }

  class FenwickTree(n: Int) extends BitIndexTree {
    private[this] val tree = Array.ofDim[Int](n)

    override def apply(i: Int) = if (i < 0) 0 else tree(i) + apply((i & (i + 1)) - 1)

    override def +=(i: Int, delta: Int) = if (i < n) {
      tree(i) += delta
      this += (i | (i + 1), delta)
    }
  }

  class UpdateableFenwickTree(n: Int) extends FenwickTree(n) {
    private[this] val data = Array.ofDim[Int](n)

    def update(i: Int, value: Int) = {
      this += (i, value - data(i))
      data(i) = value
    }
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f

  override def format(result: Result) = result mkString "\n"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

object _635D extends CodeForcesApp {
  override type Result = Seq[Long]

  override def solve(read: InputReader) = {
    val (n, k, a, b, q) = read[(Int, Int, Int, Int, Int)]
    val (fixed, broken, demand) = (new FenwickTree(n + 1), new FenwickTree(n + 1), Array.ofDim[Long](n + 1))
    var ans = Vector.empty[Long]
    repeat(q) {
      if(read[Int] == 1) {
        val (i, d) = read[(Int, Long)]
        if (demand(i) < a)  fixed(i) = d min (a - demand(i))
        if (demand(i) < b) broken(i) = d min (b - demand(i))
        demand(i) += d
      } else {
        val d = read[Int]
        val r1 = broken(1, d - 1)
        val r2 = fixed(d + k, n)
        ans = ans :+ (r1 + r2)
      }
    }
    ans
  }

  class FenwickTree(n: Int) {
    private[this] val tree = Array.ofDim[Long](n)

    def apply(i: Int): Long = if (i < 0) 0 else tree(i) + apply((i & (i + 1)) - 1)

    def apply(start: Int, end: Int): Long = this(end) - this(start - 1)

    def update(i: Int, v: Long): Unit = if (i < n) {
      tree(i) += v
      this(i | (i + 1)) = v
    }
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f

  override def format(result: Result) = result mkString "\n"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}


Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace n. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than T time units.Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T. It is guaranteed that there is at least one route from showplace 1 to showplace n such that Irina will spend no more than T time units passing it.

The first line of the input contains three integers n, m and T (2 ≤ n ≤ 5000,  1 ≤ m ≤ 5000,  1 ≤ T ≤ 109) — the number of showplaces, the number of roads between them and the time of Irina's stay in Berlatov respectively. The next m lines describes roads in Berlatov. i-th of them contains 3 integers ui, vi, ti (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ ti ≤ 109), meaning that there is a road starting from showplace ui and leading to showplace vi, and Irina spends ti time units to pass it. It is guaranteed that the roads do not form cyclic routes. It is guaranteed, that there is at most one road between each pair of showplaces.

Print the single integer k (2 ≤ k ≤ n) — the maximum number of showplaces that Irina can visit during her journey from showplace 1 to showplace n within time not exceeding T, in the first line. Print k distinct integers in the second line — indices of showplaces that Irina will visit on her route, in the order of encountering them. If there are multiple answers, print any of them.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m, t) = in.next().split(' ').map(_.toInt)
  val map = Array.fill[List[(Int, Int)]](n)(Nil)

  in.take(m).map(_.split(' ').map(_.toInt)).foreach {
    case Array(u1, v1, t1) => map(u1 - 1) ::= (v1 - 1, t1)
  }

  def topSort(): List[Int] = {
    var path = 0 :: Nil
    var visited = Set.empty[Int]
    var answer = List.empty[Int]

    while (path.nonEmpty) {
      if (path.head == n - 1 || map(path.head).forall(i => visited(i._1))) {
        answer ::= path.head
        visited += path.head
        path = path.tail
      } else {
        path ::= map(path.head).find(i => !visited(i._1)).get._1
      }
    }
    answer
  }

  def combine(a: (Int, Int, Int), list: List[(Int, Int, Int)]) = {
    if (a._1 < 0) list
    else {
      if (list.exists(l => a._1 <= l._1 && a._3 <= l._3))
        list
      else
        a :: list
    }
  }

  var answer = Array.fill[Array[Int]](n)(Array.fill(n){-1})
  var previous = Array.fill[Array[Int]](n)(Array.fill(n){-1})
  answer(0)(0) = t

  topSort().foreach {
    index =>
      answer(index).indices.foreach{
        case j =>
          val left = answer(index)(j)
          if (left != -1)
            map(index).foreach{
              case (to, time) =>
                if (left - time > answer(to)(j + 1)) {
                  answer(to)(j + 1) = left - time
                  previous(to)(j + 1) = index
                }
            }
      }
  }

  var index = n - 1
  var count = (n - 1 to 0 by -1).find(i => answer(index)(i) >= 0).get + 1
  var r = List(n)
  println(count)

  while (count != 0) {
    count -= 1
    index = previous(index)(count)
    r ::= (index + 1)
  }

  println(r.tail.mkString(" "))

}