There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)

  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o2.compareTo(o1)
      else c
    }
  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (minD > diff || maxD > diff) {
        recordResult()
        if (maxD > diff) {
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        }
        if (minD > diff) {
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        if (!ordMin.isEmpty && books(ordMin.last()) == books(i)) ordMin.pollLast()
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        if (!ordMin.isEmpty && books(ordMin.last()) == books(i)) ordMin.pollLast()
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

object P6E {
    class SegTree(m : Int, k : Int) {
        val s = 1 << Math.getExponent(m.toFloat) + 1
        val a = Array.fill(s + s){0}
        var time = 1
        def op(n : Int) = {
            def f(d : Int)(n : Int) {
                var i = s + n
                while (i > 1) {
                    val c = i ^ 1
                    val p = i >>> 1
                    if ((i & 1) == d) a(c) = time
                    a(p) = a(i) min a(c) max a(p)
                    i = p
                }
            }
            f(1)(n - k max 0)
            f(0)(n)
            val timeP = time
            time = time + 1
            timeP - a(1)
        }
    }

    def main(args : Array[String]) {
        val Array(n, k) = readLine split ' ' map {_.toInt}
        val h = readLine split ' ' map {_.toInt}
        val st = new SegTree(h.max + 1, k)
        val s = for (hi <- h) yield st op hi
        val s1 = s.max
        val r = for {
            i <- 0 until n
            if (s(i) == s1)
        } yield i + 1
        println(s1 + " " + r.size)
        for (i <- r) println(i - s1 + 1 + " " + i)
    }
}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)

  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o2.compareTo(o1)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff)
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (maxD > diff)
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt).toArray

  val deq = new java.util.LinkedList[Int]()
  var min = 0
  var max = 0
  deq.add(0)

  (1 until num) foreach { i =>
    val elem = books(i)
    val minD = math.abs(elem - books(min))
    val maxD = math.abs(elem - books(max))
    if (minD > diff) {
      recordResult()
      while (deq.getFirst != min) deq.removeFirst()
      deq.removeFirst()
      deq.addLast(i)
      findMin()
      findMax()
    } else if (maxD > diff) {
      recordResult()
      while (deq.getFirst != max) deq.removeFirst()
      deq.removeFirst()
      deq.addLast(i)
      findMin()
      findMax()
    } else {
      if (books(min) >= elem) min = i
      if (books(max) <= elem) max = i
      deq.addLast(i)
    }
  }
  recordResult()

  def findMin(): Unit = {
    var i = 0
    min = 0
    while (i < deq.size()) {
      if (books(deq.get(i)) <= books(min)) min = i
      i += 1
    }
  }

  def findMax(): Unit = {
    var i = 0
    max = 0
    while (i < deq.size()) {
      if (books(deq.get(i)) >= books(max)) max = i
      i += 1
    }
  }

  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._1 + " " + item._2)
  })

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)

  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o1.compareTo(o2)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      //if (!ordMin.isEmpty) println(books(ordMin.first()) + " " + books(ordMin.last()) + " ")
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff)
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (maxD > diff)
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt).toArray

  val deq = new java.util.LinkedList[Int]()
  var min = 0
  var max = 0
  deq.add(0)

  (1 until num) foreach { i =>
    val elem = books(i)
    val minD = math.abs(elem - books(min))
    val maxD = math.abs(elem - books(max))
    if (minD > diff) {
      recordResult()
      while (deq.getFirst != min) deq.removeFirst()
      deq.removeFirst()
      deq.addLast(i)
      findMin()
      findMax()
    } else if (maxD > diff) {
      recordResult()
      while (deq.getFirst != max) deq.removeFirst()
      deq.removeFirst()
      deq.addLast(i)
      findMin()
      findMax()
    } else {
      if (books(min) >= elem) min = i
      if (books(max) <= elem) max = i
      deq.addLast(i)
    }
  }
  recordResult()

  def findMin(): Unit = {
    var i = 0
    min = deq.getLast
    while (i < deq.size()) {
      if (books(deq.get(i)) <= books(min)) min = deq.get(i)
      i += 1
    }
  }

  def findMax(): Unit = {
    var i = 0
    max = deq.getLast
    while (i < deq.size()) {
      if (books(deq.get(i)) >= books(max)) max = deq.get(i)
      i += 1
    }
  }

  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._1 + " " + item._2)
  })

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = 10
  val diff = 1
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => Random.nextInt(3) + 1)
  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o2.compareTo(o1)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (!ordMin.isEmpty) {
        println(ordMin.first() + " " + ordMin.last() + " " + books(ordMin.first()) + " " + books(ordMin.last()) + " ")

      }
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff) {
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        } else if (maxD > diff) {
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt).toArray

  val deq = new java.util.LinkedList[Int]()

  deq.add(0)

  (1 until num) foreach { i =>
    val elem = books(i)
    val headDiff = math.abs(elem - books(deq.getFirst))
    val lastDiff = math.abs(elem - books(deq.getLast))
    if (headDiff > diff) {
      recordResult()
      deq.clear()
      deq.addFirst(i)
    } else if (lastDiff <= diff) {
      deq.addFirst(i)
    } else {
      recordResult()
      while (math.abs(elem - books(deq.getLast)) > diff) deq.removeLast()
      deq.addFirst(i)
    }
  }
  recordResult()

  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)

  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o2.compareTo(o1)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      //if (!ordMin.isEmpty) println(books(ordMin.first()) + " " + books(ordMin.last()) + " ")
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff)
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (maxD > diff)
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt).toArray

  val deq = new java.util.LinkedList[Int]()
  var min = 0
  var max = 0
  deq.add(0)

  (1 until num) foreach { i =>
    val elem = books(i)
    val minD = math.abs(elem - books(min))
    val maxD = math.abs(elem - books(max))
    if (minD > diff) {
      recordResult()
      while (deq.getLast != min) deq.removeLast()
      deq.removeFirst()
      deq.addLast(i)
      findMin()
      findMax()
    } else if (maxD > diff) {
      recordResult()
      while (deq.getLast != max) deq.removeLast()
      deq.removeFirst()
      deq.addLast(i)
      findMin()
      findMax()
    } else {
      if (books(min) >= elem) min = i
      if (books(max) <= elem) max = i
      deq.addLast(i)
    }
  }
  recordResult()

  def findMin(): Unit = {
    var i = 0
    min = deq.getLast
    while (i < deq.size()) {
      if (books(deq.get(i)) <= books(min)) min = deq.get(i)
      i += 1
    }
  }

  def findMax(): Unit = {
    var i = 0
    max = deq.getLast
    while (i < deq.size()) {
      if (books(deq.get(i)) >= books(max)) max = deq.get(i)
      i += 1
    }
  }

  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._1 + " " + item._2)
  })

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)

  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = books(o1).compareTo(books(o2))
  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff)
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (maxD > diff)
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)
  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o2.compareTo(o1)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (minD > diff || maxD > diff) {
        recordResult()
        if (maxD > diff) {
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        }
        if (minD > diff) {
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)

  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o1.compareTo(o2)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff)
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (maxD > diff)
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}

import java.util
import java.util.Comparator
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object EBooks extends App {

  val scanner = new Scanner(System.in)

  val num = scanner.nextInt()
  val diff = scanner.nextInt()
  var cnt = 0
  val buf = ArrayBuffer.empty[(Int, Int)]
  val books = (0 until num).map(i => scanner.next().toInt)
  val ordMin = new util.TreeSet[Int](new Comparator[Int] {
    override def compare(o1: Int, o2: Int): Int = {
      val c = books(o1).compareTo(books(o2))
      if (c == 0) o2.compareTo(o1)
      else c
    }

  })

  val deq = new java.util.LinkedList[Int]()
  deq.add(0)
  ordMin.add(0)

  (1 until num) foreach {
    i =>
      val elem = books(i)
      val minD = math.abs(elem - books(ordMin.first()))
      val maxD = math.abs(elem - books(ordMin.last()))
      if (minD > diff || maxD > diff) {
        recordResult()
        if (minD > diff) {
          while (deq.getLast != ordMin.first()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        } else if (maxD > diff) {
          while (!deq.isEmpty && deq.getLast != ordMin.last()) {
            ordMin.remove(deq.getLast)
            deq.removeLast()
          }
        }
        if (!deq.isEmpty) {
          ordMin.remove(deq.getLast)
          deq.removeLast()
        }
        deq.addFirst(i)
        ordMin.add(i)
      } else {
        deq.addFirst(i)
        ordMin.add(i)
      }
  }
  recordResult()
  println(cnt + " " + buf.size)
  buf.foreach(item => {
    println(item._2 + " " + item._1)
  })
  System.exit(0)

  def recordResult(): Unit = {
    if (deq.size() > cnt) {
      cnt = deq.size()
      buf.clear()
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    } else if (deq.size() == cnt) {
      buf += ((deq.getFirst + 1, deq.getLast + 1))
    }
  }

}


You are given an array $$$a_1, a_2, \dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \le i < j < k \le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 5 \cdot 10^4$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_{i - 1} \le a_i$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it in one line. If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1.

NoteIn the first test case it is impossible with sides $$$6$$$, $$$11$$$ and $$$18$$$. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle.

object CodeforcesRoundE93a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val res =
      Some((0, 1, n - 1))
        .filter { case (i, j, k) => a(i) + a(j) <= a(k) }
        .map { case (i, j, k) => (i + 1, j + 1, k + 1) }
        .map { case (i, j, k) => s"$i $j $k" }
        .getOrElse(-1)
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

import scala.io.StdIn

object Solution1 extends App {

  //A + B > C and B + C > A and C + A > B

  val n = StdIn.readLine().toInt

  val tc = for {
    _ <- 0 until n
  } yield {
    StdIn.readLine()
    StdIn.readLine().split(" ").map(_.toInt)
  }

  for {
    sides <- tc
  } {
    solve(sides)
  }

  def solve(sides: Array[Int]) = {
    var i, j, k = 0
    var result: Option[(Int, Int, Int)] = None
/*    val ssides = sides.zipWithIndex.sortBy(_._1)
    while (i < ssides.length - 2) {
      val a = ssides(i)._1
      val b = ssides(i + 1)._1
      val c = ssides(i + 2)._1

      val ai = ssides(i)._2
      val bi = ssides(i + 1)._2
      val ci = ssides(i + 2)._2

      if (!(a + b > c && b + c > a && c + a > b) && ai < bi && bi < ci) {
        result = Some((ai, bi, ci))
      }
      i += 1
    }*/
    val ssides = sides.zipWithIndex.sortBy(_._1)
    k = sides.length - 1
    while (i < sides.length - 2) {
      j = i + 1
      val a = sides(i)
      val b = sides(j)
      val c = sides(k)

      //A + B > C and B + C > A and C + A > B
      if (!(a + b > c && b + c > a && c + a > b)) {
        result = Some((i, j, k))
        i = sides.length
        j = sides.length
        k = sides.length
      }
      i += 1
    }
    /*while (i < ssides.length - 2) {
      j = i + 1
      while (j < ssides.length - 1) {
        k = ssides.length
        while (k < j) {
          val a = ssides(i)._1
          val b = ssides(j)._1
          val c = ssides(k)._1
          val ai = ssides(i)._2
          val bi = ssides(i + 1)._2
          val ci = ssides(i + 2)._2
          //A + B > C and B + C > A and C + A > B
          if (!(a + b > c && b + c > a && c + a > b) && ai < bi && bi < ci) {
            result = Some((ai, bi, ci))
            i = sides.length
            j = sides.length
            k = sides.length
          }
          k -= 1
        }
        j += 1
      }
      i += 1
    }*/
    result.map(r => println(s"${r._1 + 1} ${r._2 + 1} ${r._3 + 1}")).getOrElse(println("-1"))
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    if (an(0) + an(1) > an.last) println("-1")
    else println(s"1 2 $n")
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val n         = in.nextInt()
      val intInputs = in.line().split(" ").map(_.toInt)
      val x1        = intInputs(0)
      val x2        = intInputs(1)
      val x3        = intInputs(n - 1)

      if ((x1 + x2) <= x3 || (x1 + x3) <= x2 || (x2 + x3) <= x1) {
        println(s"1 2 $n")
      } else {
        println("-1")
      }
//      val connectivity = Array.ofDim[Boolean](airports, airports)

    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(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 scala.io.StdIn

object Solution1 extends App {

  //A + B > C and B + C > A and C + A > B

  val n = StdIn.readLine().toInt

  val tc = for {
    _ <- 0 until n
  } yield {
    StdIn.readLine()
    StdIn.readLine().split(" ").map(_.toInt)
  }

  for {
    sides <- tc
  } {
    solve(sides)
  }

  def solve(sides: Array[Int]) = {
    var i, j, k = 0
    var result: Option[(Int, Int, Int)] = None
    val ssides = sides.zipWithIndex.sortBy(_._1)
    while (i < ssides.length - 2) {
      val a = ssides(i)._1
      val b = ssides(i + 1)._1
      val c = ssides(i + 2)._1

      val ai = ssides(i)._2
      val bi = ssides(i + 1)._2
      val ci = ssides(i + 2)._2

      if (!(a + b > c && b + c > a && c + a > b) && ai < bi && bi < ci) {
        result = Some((ai, bi, ci))
      }
      i += 1
    }
    /*while (i < sides.length - 2) {
      j = i + 1
      while (j < sides.length - 1) {
        k = j + 1
        while (k < sides.length) {
          val a = sides(i)
          val b = sides(j)
          val c = sides(k)
          //A + B > C and B + C > A and C + A > B
          if (!(a + b > c && b + c > a && c + a > b)) {
            result = Some((i, j, k))
          }
          k += 1
        }
        j += 1
      }
      i += 1
    }*/
    result.map(r => println(s"${r._1 + 1} ${r._2 + 1} ${r._3 + 1}")).getOrElse(println("-1"))
  }
}


Casimir has a string $$$s$$$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions:  he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent);  or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by $$$2$$$. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with $$$s$$$ $$$=$$$ "ABCABC" he can obtain a string $$$s$$$ $$$=$$$ "ACBC" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string $$$s$$$ determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case is described by one string $$$s$$$, for which you need to determine if it can be fully erased by some sequence of turns. The string $$$s$$$ consists of capital letters 'A', 'B', 'C' and has a length from $$$1$$$ to $$$50$$$ letters, inclusive.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if there is a way to fully erase the corresponding string and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).

6
ABACAB
ABBA
AC
ABC
CABCBB
BCBCBCBCBCBCBCBC

object A extends App {

  def solitaire(s: String): Boolean = {
    val counts = Array.fill(3)(0)
    s.foreach(letter => counts(letter - 'A') += 1)
    counts(1) == counts(0) + counts(2)
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    solitaire(s) match {
      case true  => println("YES")
      case false => println("NO")
    }
  }
}

object A extends App {

  def solitaire(s: String): Boolean = {
    val as = s.count(_ == 'A')
    val bs = s.count(_ == 'B')
    val cs = s.count(_ == 'C')

    as + cs == bs
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    solitaire(s) match {
      case true  => println("YES")
      case false => println("NO")
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (left < that.left || (left == that.left && right < that.right))
                return -1
            else if (left == that.left && right == that.right)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val s = readString()
        var a = 0
        var b = 0
        var c = 0
        for (cc <- s) {
            if (cc == 'A')
                a += 1
            if (cc == 'B')
                b += 1
            if (cc == 'C')
                c += 1
        }
        if (b == a + c)
            writer.println("YES")
        else
            writer.println("NO")
    }
    writer.flush()
}


Are you going to Scarborough Fair?Parsley, sage, rosemary and thyme.Remember me to one who lives there.He once was the true love of mine.Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.Although the girl wants to help, Willem insists on doing it by himself.Grick gave Willem a string of length n.Willem needs to do m operations, each operation has four parameters l, r, c1, c2, which means that all symbols c1 in range [l, r] (from l-th to r-th, including l and r) are changed into c2. String is 1-indexed.Grick wants to know the final string after all the m operations.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). The second line contains a string s of length n, consisting of lowercase English letters. Each of the next m lines contains four parameters l, r, c1, c2 (1 ≤ l ≤ r ≤ n, c1, c2 are lowercase English letters), separated by space.

Output string s after performing m operations described above.

NoteFor the second example:After the first operation, the string is wxxak.After the second operation, the string is waaak.After the third operation, the string is gaaak.

import scala.annotation.tailrec
import scala.util.Try

object ScarboroughFair {

  def main(args: Array[String]): Unit = {
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val inputWord = scala.io.StdIn.readLine().toCharArray

    val lines = Stream
      .continually(scala.io.StdIn.readLine())
      .take(m).toList

    val output = performOperation(inputWord, lines)
    output.foreach(c => print(c))

  }

  def performOperation(inputWord: Array[Char], lines: List[String]): Array[Char] = {

    @tailrec
    def changeChar(word: Array[Char], l: Int, r: Int, oldChar: Char, newChar: Char, index: Int): Array[Char] = {
      for (i <- l to r) {
        if (word(i - 1).equals(oldChar)) word(i - 1) = newChar
      }
      if (index == lines.length - 1) return word
      else {
        val (v: Int, x: Int, c1: Char, c2: Char) = convertLinesToParameters(lines(index + 1))
        changeChar(word, v, x, c1, c2, index + 1)
      }

    }

    val (v: Int, x: Int, c1: Char, c2: Char) = convertLinesToParameters(lines(0))
    changeChar(inputWord, v, x, c1, c2, 0)
  }

  def convertLinesToParameters(line: String) = {
    val Array(v: Int, x: Int, c1: Char, c2: Char) = line.split(" ").map(s => {
      if (Try(s.toInt).isSuccess) s.toInt
      else if (Try(s.length == 1).isSuccess) s(0)
    })
    (v, x, c1, c2)
  }

}

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, m) = readInts(2)
  val s = readLine.toCharArray

  for (_ <- 0 until m) {
    val (first, second) = readLine.split(" ").splitAt(2)
    val Array(l, r) = first.map(_.toInt - 1)
    val Array(c1, c2) = second.map(_.head)

    for (i <- l to r) {
      s(i) = if (s(i) == c1) c2 else s(i)
    }
  }

  println(s.mkString)
}

object A extends App {
  def customReduce(ls: List[(Int, Char)], ops: List[(Int, Int, Char, Char)]): List[(Int, Char)] =
    if (ops.isEmpty) ls
    else {
      val op = ops.head
      val nls = ls.map((t: (Int, Char)) => {
        if (t._1 >= op._1 && t._1 <= op._2 && t._2 == op._3) (t._1, op._4)
        else t
      })
      customReduce(nls, ops.tail)
    }
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val s = scala.io.StdIn.readLine()
  val ops = (0 until m).foldLeft(List.empty[(Int, Int, Char, Char)]) { (ops, _) =>
    val Array(l, r, c1, c2) = scala.io.StdIn.readLine().split(" ")
    (l.toInt - 1, r.toInt - 1, c1(0), c2(0)) :: ops
  }.reverse

  val ls = s.foldLeft(List.empty[(Int, Char)]) ((l: List[(Int, Char)], e: Char) => {
    if (l.isEmpty) (0, e) :: l
    else (l.head._1 + 1, e) :: l
  }).reverse

  println(customReduce(ls, ops).map((e) => e._2).mkString(""))
}

/**
  * Created by AYUSH AWASTHI on 9/20/2017.
  */
import  scala.io.BufferedSource
object Basic{
  def main(args : Array[String]): Unit = {
    val tmp = Console.readLine().split(" ")
    val n = tmp(0).toInt
    val m = tmp(1).toInt
    val str = Console.readLine().toString
    var answer = str;
    var temp = str
    (1 to m).foreach {
      case i => {
        val tmp = Console.readLine().split(" ")
        val l = tmp(0).toInt
        val r = tmp(1).toInt
        val first = tmp(2).toString;
        val second = tmp(3).toString;

        temp = ""
        (0 to l-2).foreach{ case j => {
          temp+=answer(j)
        }}
        (l - 1 to r - 1).foreach { case j => {
                  if (answer.charAt(j) == first(0)) {
                    temp += second(0)
                  } else {
                    temp += answer.charAt(j)
                  }
                }
        }
        (r to str.length -1).foreach{ case j => {
          temp+=answer(j)
        }}
        answer = temp
      }
    }
    println(answer)
  }
}

object ScarboroughFair {

   def main(args: Array[String]): Unit = {
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val inputWord = scala.io.StdIn.readLine().toCharArray

    val lines = Stream
      .continually(scala.io.StdIn.readLine())
      .take(m).toList

    val output = performOperation(inputWord, lines)
    output.foreach(c => print(c))

  }

  def performOperation(inputWord: Array[Char], lines: List[String]): Array[Char] = {

    def changeChar(word: Array[Char], l: Int, r: Int, oldChar: Char, newChar: Char, index: Int): Array[Char] = {
      for (i <- l to r) {
        if (word(i - 1).equals(oldChar)) word(i - 1) = newChar
      }
      if (index == lines.length - 1) return word
      else changeChar(word, lines(index + 1).charAt(0).asDigit, lines(index + 1).charAt(2).asDigit, lines(index + 1).charAt(4), lines(index + 1).charAt(6), index + 1)

    }

    changeChar(inputWord, lines(0).charAt(0).asDigit, lines(0).charAt(2).asDigit, lines(0).charAt(4), lines(0).charAt(6), 0)
  }

}


A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.

The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.

In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val S = ns()
    val len = 10

    val cnt = Array.ofDim[Int](3, 12, 31)

    def dayLim(m: Int) = m match {
      case 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31
      case 2 => 28
      case 4 | 6 | 9 | 11 => 30
    }

    REP(S.length - len + 1) { i =>
      val d = S.substring(i, i + 2)
      val m = S.substring(i + 3, i + 5)
      val y = S.substring(i + 6, i + 10)
      if (S(i + 2) == '-' && S(i + 5) == '-')
      try {
        val dd = d.toInt
        val mm = m.toInt
        val yy = y.toInt
        if (yy >= 2013 && yy <= 2015 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= dayLim(mm)) {
          cnt(yy - 2013)(mm - 1)(dd - 1) += 1
        }
      } catch {
        case _: NumberFormatException =>
      }
    }

    val ((y, m, d), _) = (for {
      y <- 0 until 3
      m <- 0 until 12
      d <- 0 until 31
    } yield (y, m, d) -> cnt(y)(m)(d)).maxBy(_._2)

    val ans = f"${d+1}%02d-${m+1}%02d-${y+2013}"
    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable.Map

object CF158B {

  val days = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
  val cnt = Map[String, Int]().withDefaultValue(0)

  def correct(s: String): Boolean = {
    val sp = s.split("-").map(_.toInt)
    sp(0)>0 && sp(0) <= 31 && sp(1) > 0 && sp(1) <= 12 && sp(2) >= 2013 && sp(2) <= 2015 && days(sp(1) - 1) >= sp(0)
  }

  def main(args: Array[String]) {
    val s = readLine()
    """\d\d-\d\d-(?=\d\d\d\d)""".r.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    println(cnt.filterKeys(correct).maxBy(_._2)._1)
  }
}

import scala.collection.mutable.Map

object CF158B {

  val days = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

  def correct(s: String): Boolean = {
    val sp = s.split("-").map(_.toInt)
    days(sp(1) - 1) >= sp(0)
  }

  def main(args: Array[String]) {
    val cnt: Map[String, Int] = Map[String, Int]().withDefaultValue(0)
    val s = readLine()
    val r0 = """0(?=[1-9]-(0[1-9]|1[012])-201[345])""".r
    val r12 = """[12](?=[0-9]-(0[1-9]|1[012])-201[345])""".r
    val r3 = """3(?=[01]-(0[1-9]|1[012])-201[345])""".r
    r0.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    r12.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    r3.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    println(cnt.filterKeys(correct).maxBy(_._2)._1)
  }
}

import scala.collection.mutable.Map

object CF158B {

  val days = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

  def correct(s: String): Boolean = {
    val sp = s.split("-").map(_.toInt)
    days(sp(1) - 1) >= sp(0)
  }

  def main(args: Array[String]) {
    val cnt: Map[String, Int] = Map[String, Int]().withDefaultValue(0)
    val s = readLine()
    val r0 = """0(?=[1-9][- /.](0[1-9]|1[012])[- /.]201[345])""".r
    val r12 = """[12](?=[0-9][- /.](0[1-9]|1[012])[- /.]201[345])""".r
    val r3 = """3(?=[01][- /.](0[1-9]|1[012])[- /.]201[345])""".r
    r0.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    r12.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    r3.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    println(cnt.filterKeys(correct).maxBy(_._2)._1)
  }
}

object CF260B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  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 solve = {
    var s: Seq[Char] = nextString
    val n = s.length
    var r: Map[String, Int] = Map()

    for (i <- 0 until n - 9) {
      if (s(i).isDigit && s(i + 1).isDigit) {
        val d = ("" + s(i) + s(i + 1)).toInt
        if (s(i + 2) == '-') {
          if (s(i + 3).isDigit && s(i + 4).isDigit) {
            val m = ("" + s(i + 3) + s(i + 4)).toInt
            if (s(i + 5) == '-') {
              if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {
                val y = ("" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt
                var valid = false
                if (y >= 2013 && y <= 2015) {
                  if (m >= 1 && m <= 12) {
                    if (d >= 1 && d <= 31) {
                      valid = m match {
                        case 2 => (d <= 28)
                        case 4 | 6 | 9 | 11 => (d <= 30)
                        case _ => true
                      }
                    }
                  }
                }
                if (valid) {
                  val date = (for (j <- i until i + 10) yield s(j)).mkString
                  var counter = 1
                  if (r.contains(date)) {
                    counter = r(date) + 1
                  }
                  r += (date -> counter)
                }
              }
            }
          }
        }
      }
    }

    var c = 0
    var doomsday = ""
    r.keys foreach { k =>
       if (r(k) > c) {
         c = r(k)
         doomsday = k
       }
    }

    out.println(doomsday)
  }

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

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val S = ns()
    val len = 10

    val cnt = Array.ofDim[Int](3, 12, 31)

    def dayLim(m: Int) = m match {
      case 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31
      case 2 => 28
      case 4 | 6 | 9 | 11 => 30
    }

    REP(S.length - len + 1) { i =>
      val d = S.substring(i, i + 2)
      val m = S.substring(i + 3, i + 5)
      val y = S.substring(i + 6, i + 10)
      try {
        val dd = d.toInt
        val mm = m.toInt
        val yy = y.toInt
        if (yy >= 2013 && yy <= 2015 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= dayLim(mm)) {
          cnt(yy - 2013)(mm - 1)(dd - 1) += 1
        }
      } catch {
        case _: NumberFormatException =>
      }
    }

    val ((y, m, d), _) = (for {
      y <- 0 until 3
      m <- 0 until 12
      d <- 0 until 31
    } yield (y, m, d) -> cnt(y)(m)(d)).maxBy(_._2)

    val ans = f"${d+1}%02d-${m+1}%02d-${y+2013}"
    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable.Map

object CF158B {
  def main(args: Array[String]) {
    val cnt: Map[String, Int] = Map[String, Int]().withDefaultValue(0)
    val s = readLine()
    val r0 = """0(?=[1-9][- /.](0[1-9]|1[012])[- /.]201[345])""".r
    val r12 = """[12](?=[0-9][- /.](0[1-9]|1[012])[- /.]201[345])""".r
    val r3 = """3(?=[01][- /.](0[1-9]|1[012])[- /.]201[345])""".r
    r0.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    r12.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    r3.findAllIn(s).matchData.foreach(x => cnt(s.substring(x.start, x.start + 10)) += 1)
    println(cnt.maxBy(_._2)._1)
  }
}

object CF260B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  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 solve = {
    var s: String = nextString
    val n = s.length

    val m = doomsdays(s).groupBy(x => x).mapValues(x => x.length)
    var c = 0
    var doomsday = ""
    m.keys foreach { k =>
      if (m(k) > c) {
        c = m(k)
        doomsday = k
      }
    }

    out.println(doomsday)
  }

  val DoomsDay = """^(\d\d)-(\d\d)-(\d\d\d\d).*""".r

  def doomsdays(s: String): List[String] = s match {
    case s: String if (s.length == 0) => Nil
    case DoomsDay(d, m, y) =>
      val dd = d.toInt
      val mm = m.toInt
      val yy = y.toInt
      var valid = false
      if (yy >= 2013 && yy <= 2014) {
        if (mm >= 1 && mm <= 12) {
          if (dd >= 0 && dd <= 31) {
            if (mm % 2 == 0) {
              if (mm == 1 && dd <= 28) {
                valid = true
              } else if (mm != 1 && dd <= 30) {
                valid = true
              }
            } else {
              valid = true
            }
          }
        }
      }
      if (valid) d + "-" + m + "-" + y :: doomsdays(s.tail) else doomsdays(s.tail)
    case _ => doomsdays(s.tail)
  }

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

object CF260B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  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 solve = {
    var s: Seq[Char] = nextString
    val n = s.length
    var r: Map[String, Int] = Map()

    for (i <- 0 until n - 10) {
      if (s(i).isDigit && s(i + 1).isDigit) {
        val d = ("" + s(i) + s(i + 1)).toInt
        if (s(i + 2) == '-') {
          if (s(i + 3).isDigit && s(i + 4).isDigit) {
            val m = ("" + s(i + 3) + s(i + 4)).toInt
            if (s(i + 5) == '-') {
              if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {
                val y = ("" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt
                var valid = false
                if (y >= 2013 && y <= 2015) {
                  if (m >= 1 && m <= 12) {
                    if (d >= 1 && d <= 31) {
                      valid = m match {
                        case 2 => (d <= 28)
                        case 4 | 6 | 9 | 11 => (d <= 30)
                        case _ => true
                      }
                    }
                  }
                }
                if (valid) {
                  val date = (for (j <- i until i + 10) yield s(j)).mkString
                  var counter = 1
                  if (r.contains(date)) {
                    counter = r(date) + 1
                  }
                  r += (date -> counter)
                }
              }
            }
          }
        }
      }
    }

    var c = 0
    var doomsday = ""
    r.keys foreach { k =>
       if (r(k) > c) {
         c = r(k)
         doomsday = k
       }
    }

    out.println(doomsday)
  }

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

object CF260B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  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 solve = {
    var s: String = nextString
    val n = s.length

    val DoomsDay = """(\d\d)-(\d\d)-(\d\d\d\d)""".r
    var l: List[String] = Nil

    for(mm <- DoomsDay.findAllIn(s).matchData) {
      val d = mm.group(1).toInt
      val m = mm.group(2).toInt
      val y = mm.group(3).toInt
      var valid = false
      if (y >= 2013 && y <= 2014) {
        if (m >= 1 && m <= 12) {
          if (d >= 0 && d <= 31) {
            if (m % 2 == 0) {
              if (m == 1 && d <= 28) {
                valid = true
              } else if (m != 1 && d <= 30) {
                valid = true
              }
            } else {
              valid = true
            }
          }
        }
      }

      if (valid) {
        l = mm.group(0) :: l
      }
    }

    val m = l.groupBy(x => x).mapValues(x => x.length)
    var c = 0
    var doomsday = ""
    m.keys foreach { k =>
       if (m(k) > c) {
         c = m(k)
         doomsday = k
       }
    }

    out.println(doomsday)
  }

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

object CF260B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  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 solve = {
    var s: Seq[Char] = nextString
    val n = s.length
    var r: Map[String, Int] = Map()

    for (i <- 0 until n - 10) {
      if (s(i).isDigit && s(i + 1).isDigit) {
        val d = ("" + s(i) + s(i + 1)).toInt
        if (s(i + 2) == '-') {
          if (s(i + 3).isDigit && s(i + 4).isDigit) {
            val m = ("" + s(i + 3) + s(i + 4)).toInt
            if (s(i + 5) == '-') {
              if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {
                val y = ("" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt
                var valid = false
                if (y >= 2013 && y <= 2014) {
                  if (m >= 1 && m <= 12) {
                    if (d >= 0 && d <= 31) {
                      if (m % 2 == 0) {
                        if (m == 1 && d <= 28) {
                          valid = true
                        } else if (m != 1 && d <= 30) {
                          valid = true
                        }
                      } else {
                        valid = true
                      }
                    }
                  }
                }
                if (valid) {
                  val date = (for (j <- i until i + 10) yield s(j)).mkString
                  var counter = 1
                  if (r.contains(date)) {
                    counter = r(date) + 1
                  }
                  r += (date -> counter)
                }
              }
            }
          }
        }
      }
    }

    var c = 0
    var doomsday = ""
    r.keys foreach { k =>
       if (r(k) > c) {
         c = r(k)
         doomsday = k
       }
    }

    out.println(doomsday)
  }

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

object CF260B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  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 solve = {
    var s: Seq[Char] = nextString
    val n = s.length
    var r: Map[String, Int] = Map()

    for (i <- 0 until n - 10) {
      if (s(i).isDigit && s(i + 1).isDigit) {
        val d = ("" + s(i) + s(i + 1)).toInt
        if (s(i + 2) == '-') {
          if (s(i + 3).isDigit && s(i + 4).isDigit) {
            val m = ("" + s(i + 3) + s(i + 4)).toInt
            if (s(i + 5) == '-') {
              if (s(i + 6).isDigit && s(i + 7).isDigit && s(i + 8).isDigit && s(i + 9).isDigit) {
                val y = ("" + s(i + 6) + s(i + 7) + s(i + 8) + s(i + 9)).toInt
                var valid = false
                if (y >= 2013 && y <= 2015) {
                  if (m >= 1 && m <= 12) {
                    if (d >= 0 && d <= 31) {
                      if (m % 2 == 0) {
                        if (m == 1 && d <= 28) {
                          valid = true
                        } else if (m != 1 && d <= 30) {
                          valid = true
                        }
                      } else {
                        valid = true
                      }
                    }
                  }
                }
                if (valid) {
                  val date = (for (j <- i until i + 10) yield s(j)).mkString
                  var counter = 1
                  if (r.contains(date)) {
                    counter = r(date) + 1
                  }
                  r += (date -> counter)
                }
              }
            }
          }
        }
      }
    }

    var c = 0
    var doomsday = ""
    r.keys foreach { k =>
       if (r(k) > c) {
         c = r(k)
         doomsday = k
       }
    }

    out.println(doomsday)
  }

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


Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.

The first line contains three integers n, m and x (2 ≤ n ≤ 50, 1 ≤ m ≤ 500, 1 ≤ x ≤ 100 000) — the number of nodes, the number of directed edges and the number of bears, respectively. Each of the following m lines contains three integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.

Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample, Niwel has three bears. Two bears can choose the path , while one bear can choose the path . Even though the bear that goes on the path  can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.

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 maxFlow(cap: Array[Array[Long]], s: Int, t: Int): Long = {

    val n = cap.size
    val untilN = 0 until n
    var flow = 0L

    val adj = Array.fill(n, n)(0)
    val deg = Array.fill(n)(0)

    for (u <- untilN) {
      for (v <- untilN) if (cap(u)(v) != 0 && u != v) {
        adj(u)(deg(u)) = v
        deg(u) += 1
        //adj(v)(deg(v)) = u
        //deg(v) += 1
      }
    }

    var done = false
    val q = Array.fill(n)(-1) // BFS stuff

    while (!done) {

      // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable
      val prev = Array.fill(n)(-1)

      // find an augmenting path
      var qf = 0
      var qb = 1
      q(0) = s
      prev(s) = -2
      while (qb > qf && prev(t) == -1) {
        val u = q(qf)
        qf += 1
        for (i <- 0 until deg(u)) {
          val v = adj(u)(i)
          if (prev(v) == -1 && cap(u)(v) != 0) {
            q(qb) = v
            qb += 1
            prev(v) = u
          }
        }
      }

      if (prev(t) == -1) done = true
      else  // try finding more paths:
        for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {
          var bot = cap(z)(t)
          var v = z
          var u = prev(v)
          while (u >= 0) {
            bot = math.min(bot, cap(u)(v))
            v = u
            u = prev(v)
          }

          if (bot != 0) {

            cap(z)(t) -= bot
            cap(t)(z) += bot

            v = z
            u = prev(v)
            while (u >= 0) {
              cap(u)(v) -= bot
              cap(v)(u) += bot
              v = u
              u = prev(v)
            }

            flow += bot
          }
        }
    }

    flow
  }

  val Array(n, m, x) = readInts(3)
  val ws = Array.fill(n, n){ 0L }

  for (_ <- 0 until m) {
    val Array(a, b, c) = readInts(3)
    ws(a - 1)(b - 1) = c
  }

  def can(c: Double): Boolean = {
    val caps = ws.map {
      _.map {
        w => if (w == 0) 0 else {
          if (x * c > w) (w / c).floor.toLong else x
        }
      }
    }
    maxFlow(caps, 0, n - 1) >= x
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
    if (depth > 60) (lo + hi) / 2
    else {
      val mid = (lo + hi) / 2
      if (can(mid)) binSearchD(mid, hi, depth + 1)
      else binSearchD(lo, mid, depth + 1)
    }
  }

  println(x * binSearchD(0.1d / x, 10000000d, 0))
}

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 maxFlow(cap: Array[Array[Long]], s: Int, t: Int): Long = {

    val n = cap.size
    val untilN = 0 until n
    var flow = 0L

    val adj = Array.fill(n, n)(0)
    val deg = Array.fill(n)(0)

    for (u <- untilN) {
      for (v <- untilN) if (cap(u)(v) != 0 && u != v) {
        adj(u)(deg(u)) = v
        deg(u) += 1
        //adj(v)(deg(v)) = u
        //deg(v) += 1
      }
    }

    var done = false
    val q = Array.fill(n)(-1) // BFS stuff

    while (!done) {

      // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable
      val prev = Array.fill(n)(-1)

      // find an augmenting path
      var qf = 0
      var qb = 1
      q(0) = s
      prev(s) = -2
      while (qb > qf && prev(t) == -1) {
        val u = q(qf)
        qf += 1
        for (i <- 0 until deg(u)) {
          val v = adj(u)(i)
          if (prev(v) == -1 && cap(u)(v) != 0) {
            q(qb) = v
            qb += 1
            prev(v) = u
          }
        }
      }

      if (prev(t) == -1) done = true
      else  // try finding more paths:
        for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {
          var bot = cap(z)(t)
          var v = z
          var u = prev(v)
          while (u >= 0) {
            bot = math.min(bot, cap(u)(v))
            v = u
            u = prev(v)
          }

          if (bot != 0) {

            cap(z)(t) -= bot
            cap(t)(z) += bot

            v = z
            u = prev(v)
            while (u >= 0) {
              cap(u)(v) -= bot
              cap(v)(u) += bot
              v = u
              u = prev(v)
            }

            flow += bot
          }
        }
    }

    flow
  }

  val Array(n, m, x) = readInts(3)
  val ws = Array.fill(n, n){ 0L }

  for (_ <- 0 until m) {
    val Array(a, b, c) = readInts(3)
    ws(a - 1)(b - 1) = c
  }

  def can(c: Double): Boolean = {
    val caps = ws.map {
      _.map {
        w => if (w == 0) 0 else {
          var y = x.toLong
          try {
            y = if (x * c > w) (w / c).floor.toLong else x
          } catch {
            case _: Exception =>
          }
          y
        }
      }
    }
    maxFlow(caps, 0, n - 1) >= x
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
    //println(depth, lo, hi)
    if (depth > 50 || math.abs(hi - lo) < 1E-7d || hi / lo < 1d + 1E-7d) (lo + hi) / 2
    else {
      val mid = (lo + hi) / 2
      if (can(mid)) binSearchD(mid, hi, depth + 1)
      else binSearchD(lo, mid, depth + 1)
    }
  }

  println(x * binSearchD(1d / x, 1000000d, 0))
}

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 maxFlow(cap: Array[Array[Long]], s: Int, t: Int): Long = {

    val n = cap.size
    val untilN = 0 until n
    var flow = 0L

    val adj = Array.fill(n, n)(0)
    val deg = Array.fill(n)(0)

    for (u <- untilN) {
      for (v <- untilN) if (cap(u)(v) != 0) {
        adj(u)(deg(u)) = v
        deg(u) += 1
        adj(v)(deg(v)) = u
        deg(v) += 1
      }
    }

    var done = false
    val q = Array.fill(n)(-1) // BFS stuff

    while (!done) {

      // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable
      val prev = Array.fill(n)(-1)

      // find an augmenting path
      var qf = 0
      var qb = 1
      q(0) = s
      prev(s) = -2
      while (qb > qf && prev(t) == -1) {
        val u = q(qf)
        qf += 1
        for (i <- 0 until deg(u)) {
          val v = adj(u)(i)
          if (prev(v) == -1 && cap(u)(v) != 0) {
            q(qb) = v
            qb += 1
            prev(v) = u
          }
        }
      }

      if (prev(t) == -1) done = true
      else  // try finding more paths:
        for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {
          var bot = cap(z)(t)
          var v = z
          var u = prev(v)
          while (u >= 0) {
            bot = math.min(bot, cap(u)(v))
            v = u
            u = prev(v)
          }

          if (bot != 0) {

            cap(z)(t) -= bot
            cap(t)(z) += bot

            v = z
            u = prev(v)
            while (u >= 0) {
              cap(u)(v) -= bot
              cap(v)(u) += bot
              v = u
              u = prev(v)
            }

            flow += bot
          }
        }
    }

    flow
  }

  val Array(n, m, x) = readInts(3)
  val ws = Array.fill(n, n){ 0 }

  for (_ <- 0 until m) {
    val Array(a, b, c) = readInts(3)
    ws(a - 1)(b - 1) = c
  }

  def can(c: Double): Boolean = {
    val caps = ws.map {
      _.map {
        w => (w / c).floor.toLong
      }
    }
    maxFlow(caps, 0, n - 1) >= x
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
    if (depth > 20 || math.abs(hi - lo) < 1E-7d || hi / lo < 1d + 1E-7d) (lo + hi) / 2
    else {
      val mid = (lo + hi) / 2
      if (can(mid)) binSearchD(mid, hi, depth + 1)
      else binSearchD(lo, mid, depth + 1)
    }
  }

  println(x * binSearchD(0.8d / x, 10000000d, 0))
}

import scala.collection._

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

  def maxFlow(cap: Array[Array[Int]], s: Int, t: Int): Int = {

    val n = cap.size
    val untilN = 0 until n
    var flow = 0

    val adj = Array.fill(n, n)(0)
    val deg = Array.fill(n)(0)

    for (u <- untilN) {
      for (v <- untilN) if (cap(u)(v) != 0) {
        adj(u)(deg(u)) = v
        deg(u) += 1
        adj(v)(deg(v)) = u
        deg(v) += 1
      }
    }

    var done = false
    val q = Array.fill(n)(-1) // BFS stuff

    while (!done) {

      // prev contains the minimum cut. If prev(v) == -1, then v is not reachable from s; otherwise, it is reachable
      val prev = Array.fill(n)(-1)

      // find an augmenting path
      var qf = 0
      var qb = 1
      q(0) = s
      prev(s) = -2
      while (qb > qf && prev(t) == -1) {
        val u = q(qf)
        qf += 1
        for (i <- 0 until deg(u)) {
          val v = adj(u)(i)
          if (prev(v) == -1 && cap(u)(v) != 0) {
            q(qb) = v
            qb += 1
            prev(v) = u
          }
        }
      }

      if (prev(t) == -1) done = true
      else  // try finding more paths:
        for (z <- untilN) if (cap(z)(t) != 0 && prev(z) != -1) {
          var bot = cap(z)(t)
          var v = z
          var u = prev(v)
          while (u >= 0) {
            bot = math.min(bot, cap(u)(v))
            v = u
            u = prev(v)
          }

          if (bot != 0) {

            cap(z)(t) -= bot
            cap(t)(z) += bot

            v = z
            u = prev(v)
            while (u >= 0) {
              cap(u)(v) -= bot
              cap(v)(u) += bot
              v = u
              u = prev(v)
            }

            flow += bot
          }
        }
    }

    flow
  }

  val Array(n, m, x) = readInts(3)
  val ws = Array.fill(n, n){ 0 }

  for (_ <- 0 until m) {
    val Array(a, b, c) = readInts(3)
    ws(a - 1)(b - 1) = c
  }

  def can(c: Double): Boolean = {
    val caps = ws.map {
      _.map {
        w => (w / c).floor.toInt
      }
    }
    maxFlow(caps, 0, n - 1) >= x
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double): Double = {
    if (math.abs(hi - lo) < 1E-6) hi
    else {
      val mid = (lo + hi) / 2
      if (can(mid)) binSearchD(mid, hi)
      else binSearchD(lo, mid)
    }
  }

  println(x * binSearchD(0.8d / x, 10000000d))
}


Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.

Print a single integer — the required maximal xor of a segment of consecutive elements.

NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  in.next()
  val data = in.next().split(' ').map(_.toInt)
  println(data.indices.foldLeft(data.last) {
    case (max, i) => Math.max(max, (i + 1 until data.length).foldLeft((data(i), data(i))) {
      case((nMax, soFar), j) =>
        val nSoFar = soFar ^ data(j)
        (Math.max(nSoFar, nMax), nSoFar)
    }._1)
  })
}

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

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  val res = {
    for {
      i <- 0 to N
      j <- (i + 1) to N
    }
    yield {
      A.slice(i, j).foldLeft(0)(_ ^ _)
    }
  }.max
  out.println(res)
  out.close
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    var max=0
    for(i<-0 until n)
    	for(j<-i+1 to n)
    		max=math.max(max,a.slice(i,j).reduce(_^_))
    println(max)
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    var max=0
    for(i<-0 until n)
    {
    	var value=a(i)
    	max=math.max(max,a(i))
    	for(j<-i+1 until n)
    	{
    		value^=a(j)
    		max=math.max(max,value)
    	}
    }
    println(max)
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    val b=for(i<-0 until n) yield
    	for(j<-i+1 to n) yield
    		a.slice(i,j).reduce(_^_)

    println(b.reduce(_++_).max)
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    println((for(i<-0 until n) yield
    	for(j<-i+1 to n) yield
    		a.slice(i,j).reduce(_^_)).reduce(_++_).max)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val all = for(i <- 0 until n; j <- i + 1 to n) yield(a.drop(i).take(j - i)).foldLeft(0)(_ ^ _)
    println(all.max)
  }
}

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

    val n =readLine.toInt
    val a =readLine.split(" ").map(_.toInt)

    println(
      (0 until n).flatMap{
        i=>
        (i until n).map(jj=>(i,jj))
      }.map{
        case(i,jj)=>
        a.slice(i,jj+1).reduce((x,y)=>x^y)
      }.max
    )
  }
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    var max=0
    for(i<-0 until n)
    {
    	var value=a(i)
    	max=math.max(max,a(i))
    	for(j<-i+1 until n)
    	{
    		value|=a(j)
    		max=math.max(max,value)
    	}
    }
    println(max)
}

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

    val n =readLine.toInt
    val a =readLine.split(" ").map(_.toInt)

    println(
      (0 until n).combinations(2).map{l=>
        val(i,jj)=(l(0),l(1))
        a.slice(i,jj+1).reduce((x,y)=>x^y)
      }.max
    )
  }
}