Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.   However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.

First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique.

NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number.

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).sorted
  val attackedSet = attacked.toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3, d4 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int, depth: Int): Unit = {
    d3(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)
  }

  def dfs4(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))
    d4(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attackedSet(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var u2 = attacked.min
    for (u <- attacked) {
      if ((d1(u) max d2(u)) > (d1(u2) max d2(u2))) {
        u2 = u
      }
    }
    dfs3(u2, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if ((d1(u) max d2(u) max d3(u)) > (d1(start) max d2(start) max d3(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs4(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))
    d3(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    dfs2(attacked.max, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs3(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3, d4 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int, depth: Int): Unit = {
    d3(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)
  }

  def dfs4(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))
    d4(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var u2 = attacked.min
    for (u <- attacked) {
      if ((d1(u) max d2(u)) > (d1(u2) max d2(u2))) {
        u2 = u
      }
    }
    dfs3(u2, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if ((d1(u) max d2(u) max d3(u)) > (d1(start) max d2(start) max d3(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs4(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).sorted
  val attackedSet = attacked.toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))
    d3(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attackedSet(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    dfs2(attacked.max, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs3(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))
    d3(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    dfs2(attacked.max, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs3(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).sorted
  val attackedSet = attacked.toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))
    d3(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attackedSet(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs3(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3, d4 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int, depth: Int): Unit = {
    d3(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)
  }

  def dfs4(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))
    d4(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var u2 = attacked.min
    for (u <- attacked) {
      if (d2(u) > d2(u2)) {
        u2 = u
      }
    }
    dfs3(u2, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if ((d2(u) max d3(u)) > (d2(start) max d3(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs4(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3, d4 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int, depth: Int): Unit = {
    d3(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)
  }

  def dfs4(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))
    d4(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var u2 = attacked.min
    for (u <- attacked) {
      if (d2(u) > d2(u2)) {
        u2 = u
      }
    }
    dfs3(u2, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if ((d1(u) max d2(u) max d3(u)) > (d1(start) max d2(start) max d3(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs4(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs3(v, u))
    d3(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs3(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3, d4 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int, depth: Int): Unit = {
    d3(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)
  }

  def dfs4(u: Int, prev: Int): Int = {
    var max = 0
    for (v <- adjs(u)) if (v != prev && sizes(v) > 0) max = math.max(max, dfs4(v, u))
    d4(u) = max + 1
    max + 1
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d4)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min + 1)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    var u1 = attacked.min
    for (u <- attacked) {
      if (d1(u) > d1(u1)) {
        u1 = u
      }
    }
    dfs2(u1, -1, 0)
    var u2 = attacked.min
    for (u <- attacked) {
      if (d2(u) > d2(u2)) {
        u2 = u
      }
    }
    dfs3(u2, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if ((d3(u)) > (d3(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs4(start, -1)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

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

  val Array(n, m) = readInts(2)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u) += v
    adjBuilders(v) += u
  }

  val attacked = readInts(m).map(_ - 1).toSet

  val adjs = adjBuilders.map(_.result)

  val d1, d2, d3 = Array.ofDim[Int](n)

  def dfs1(u: Int, prev: Int, depth: Int): Unit = {
    d1(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs1(v, u, depth + 1)
  }

  def dfs2(u: Int, prev: Int, depth: Int): Unit = {
    d2(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs2(v, u, depth + 1)
  }

  def dfs3(u: Int, prev: Int, depth: Int): Unit = {
    d3(u) = depth
    for (v <- adjs(u)) if (v != prev) dfs3(v, u, depth + 1)
  }

  val sizes = Array.ofDim[Int](n)

  def size(u: Int, prev: Int): Int = {
    var s = if (attacked(u)) 1 else 0
    for (v <- adjs(u)) if (v != prev) s += size(v, u)
    sizes(u) = s
    s
  }

  def steps(u: Int, prev: Int, goBack: Boolean): Int = {
    val as = adjs(u).filter(v => v != prev && sizes(v) > 0).sortBy(d3)
    var s = if (goBack) 2 else 1
    for (i <- 0 until as.length - 1) s += steps(as(i), u, true)
    if (as.length > 0) s += steps(as.last, u, goBack)
    s
  }

  if (m == 1) {
    println(attacked.min)
    println(0)
  } else {
    dfs1(attacked.min, -1, 0)
    dfs2(attacked.max, -1, 0)
    var start = attacked.min
    for (u <- attacked) {
      if (math.max(d1(u), d2(u)) > math.max(d1(start), d2(start))) {
        start = u
      }
    }
    size(start, -1)
    dfs3(start, -1, 0)
    println(start + 1)
    println(steps(start, -1, false) - 1)
  }
}


Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?

The first line contains two integers n and k (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105). The next line contains n characters — the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#". It is guaranteed that the first and the last characters equal ".".

Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).

import scala.io.StdIn

/**
 * @author chengyi
 */
object KsushaSquirrel {

  def canPass(line:String, k:Int):String={
    //find the biggest consecutive #
    var num:Int = 0
    var maxNum:Int = 0
    for (a<-0 to line.length-1){
      val cur = line(a)
      if (cur=='#'){
        num = num + 1
        maxNum = Math.max(num, maxNum)
      }else if (cur=='.'){
        num = 0
      }
    }
    if (maxNum<k){
      return "YES"
    }else{
      return "NO"
    }
  }

  def main(args:Array[String]){
    val nk = StdIn.readLine().split(" ").map{x=>x.toInt}
    val n = nk(0)
    val k = nk(1)
    val line = StdIn.readLine()
    println(canPass(line, k))
  }

}


Keshi is throwing a party and he wants everybody in the party to be happy.He has $$$n$$$ friends. His $$$i$$$-th friend has $$$i$$$ dollars. If you invite the $$$i$$$-th friend to the party, he will be happy only if at most $$$a_i$$$ people in the party are strictly richer than him and at most $$$b_i$$$ people are strictly poorer than him.Keshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 10^4)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the number of Keshi's friends. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ $$$(0 \le a_i, b_i < n)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the maximum number of people Keshi can invite.

NoteIn the first test case, he invites the first and the second person. If he invites all of them, the third person won't be happy because there will be more than $$$1$$$ person poorer than him.

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

object Main2 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 fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b:  Int, c: Double)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (b == that.b)
                return -1 * c.compareTo(that.c)
            else
                return -1 * b.compareTo(that.b)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val a = new Array[Int](n+1)
        val b = new Array[Int](n+1)
        for (i <- 1 to n) {
            a(i) = readInt()
            b(i) = readInt()
        }
        def check(kk: Int): Boolean = {
            var sz = 0
            for (i <- 1 to n) {
                if (a(i) >= kk-sz-1 && b(i) >= sz)
                    sz += 1
            }
            if (sz >= kk)
                return true
            else
                return false
        }
        def bs(st:Int, en:Int): Int = {
            if (en - st <= 1) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
        writer.println(bs(1, n))
    }
    writer.flush()
}


In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways:   If server is free and query queue is empty, then server immediately starts to process this query.  If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue.  If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.

The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue. Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.

Print the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or  - 1 if the corresponding query will be rejected.

NoteConsider the first sample.   The server will start to process first query at the moment 2 and will finish to process it at the moment 11.  At the moment 4 second query appears and proceeds to the queue.  At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected.  At the moment 11 server will finish to process first query and will take the second query from the queue.  At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue.  At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there.  Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue.  Server finishes to process query number 5 at the moment 22.

import scala.collection._

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, b) = readInts(2)
  val res = Array.fill(n) { -1L }

  case class Task(id: Int, t: Int, d: Int)

  val tasks = Array.tabulate(n) { id =>
    val Array(t, d) = readInts(2)
    Task(id, t, d)
  }.sortBy(_.t)

  val queue = mutable.Queue.empty[Task]

  var time = 0L
  for (i <- tasks.indices) {
    val task = tasks(i)
    while (time <= task.t && queue.nonEmpty) {
      val queued = queue.dequeue()
      time += queued.d
      res(queued.id) = time
    }
    if (time < task.t) time = task.t
    if (queue.size < b) queue += task
  }

  while (queue.nonEmpty) {
    val queued = queue.dequeue()
    time += queued.d
    res(queued.id) = time
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString(" "))
  Console.flush
}

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

object Solution {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines.toList
    val (firstLine, rest) =
      lines match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, queueSize) =
      firstLine.split(" ") match {
        case Array(x, y) => (x.toInt, y.toInt)
      }

    val jobs = (for {
      line <- rest.zipWithIndex
    } yield parseLine(line)).toList

    val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)
    finishedJobs.foreach(x => print(x.getEndTime + " "))
    println
  }

  def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {
    val queue = Queue[PendingJob]()
    val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]
    val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]

    def queuePendingJobs(curTime: Long) = {
      while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {
        val head = remainingJobs.remove(0)
        if (queue.size == queueSize) {
          finishedJobs += head.fail
        } else {
          queue enqueue head
        }
      }
    }

    def getNextRunningJob(curTime: Long): Option[PendingJob] = {
      if (!queue.isEmpty) {
        val job = queue.dequeue
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {
        val job = remainingJobs.remove(0)
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else
        None
    }

    def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {
      if (queue.isEmpty && remainingJobs.isEmpty) {
        finishedJobs.toVector
      } else if (!queue.isEmpty && remainingJobs.isEmpty) {
        var currentTime = curTime
        while (!queue.isEmpty) {
          val curJob = queue.dequeue
          val runJob = curJob.run(currentTime)
          finishedJobs += runJob
          currentTime = currentTime + curJob.processTime
        }
        finishedJobs.toVector
      } else {
        queuePendingJobs(curTime)

        val f = () => {
          val nextJob = getNextRunningJob(curTime)
          nextJob match {
            case Some(y) => {
              val completeNextJob = y.run(curTime)
              Some(completeNextJob)
            }
            case _ => None
          }
        }
        val nextRunningJob: Option[CompleteJob] =
          curJob match {
            case Some(x) if (x.endTime <= curTime) => f()
            case Some(x) => Some(x)
            case None => f()
          }

        val getNextStartTime: Long =
          nextRunningJob match {
            case Some(x) => x.endTime
            case None    => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1
          }
        loop(nextRunningJob, getNextStartTime)
      }
    }

    loop(None, 0)
  }

  def parseLine(line: Tuple2[String, Int]): PendingJob = {
    line._1.split(" ") match {
      case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)
    }
  }

}

case class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {
  def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)
  def fail: FailedJob = FailedJob(id)
}
trait FinishedJob {
  def getId: Int
  def getEndTime: Long
}
case class CompleteJob(id: Int, endTime: Long) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = endTime
}
case class FailedJob(id: Int) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = -1L
}

import scala.collection._

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, b) = readInts(2)
  val res = Array.fill(n) { -1 }

  case class Task(id: Int, t: Int, d: Int)

  val tasks = Array.tabulate(n) { id =>
    val Array(t, d) = readInts(2)
    Task(id, t, d)
  }.sortBy(_.t)

  val queue = mutable.Queue.empty[Task]

  var time = 0
  for (i <- tasks.indices) {
    val task = tasks(i)
    while (time <= task.t && queue.nonEmpty) {
      val queued = queue.dequeue()
      time += queued.d
      res(queued.id) = time
    }
    if (time < task.t) time = task.t
    if (queue.size < b) queue += task
  }

  while (queue.nonEmpty) {
    val queued = queue.dequeue()
    time += queued.d
    res(queued.id) = time
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString(" "))
  Console.flush
}

import scala.collection.immutable.Queue

object Solution {

  def main(args: Array[String]): Unit = {
    val (firstLine, lines) =
      scala.io.Source.stdin.getLines.toList match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, sizeOfQueue) =
      firstLine.split(" ").map(_.toInt) match {
        case Array(x, y) => (x, y)
      }

    val jobs: List[PendingJob] =
      for {
        lineWithIndex <- lines.zipWithIndex
      } yield parseJob(lineWithIndex._1, lineWithIndex._2)

    processJobs(jobs, numQueries, sizeOfQueue).sortWith(_.index < _.index).foreach(x => print(x + " "))
    println
  }

  def processJobs(jobs: List[PendingJob], numQueries: Int, sizeOfQueue: Int): Vector[FinishedJob] = {
    @scala.annotation.tailrec
    def loop(curJob: Option[RunningJob], remainingJobs: List[PendingJob], queue: Queue[PendingJob], curTime: Long, processedJobs: Vector[FinishedJob]): Vector[FinishedJob] = {
      def getNextStartTime = {
        remainingJobs match {
          case x::_ => x.arrivalTime
          case Nil => curJob.get.endTime
        }
      }
      if (remainingJobs.isEmpty && queue.isEmpty) {
        processedJobs
      } else {
        val (currentlyArrivingJob, newRemainingJobs) =
          remainingJobs match {
            case x::xs if x.arrivalTime == curTime => (Some(x), xs)
            case _ => (None, remainingJobs)
          }

        val curRunningJob: Option[RunningJob] =
          curJob match {
            case Some(x) if x.endTime <= curTime => None
            case _ => curJob
          }
        var nextStartTime = curTime + 1
        val (nextRunningJob, newQueue, newProcessedJobs) =
          (currentlyArrivingJob, curRunningJob) match {
            case (None, Some(_)) => {
              nextStartTime = getNextStartTime
              (curRunningJob, queue, processedJobs)
            }
            case (None, None) => {
              if (queue.isEmpty) {
                nextStartTime = getNextStartTime
                (None, queue, processedJobs)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q, processedJobs :+ newRunningJob)
              }
            }
            case (Some(x), None) => {
              if (queue.isEmpty) {
                val newRunningJob = x.start(curTime)
                (Some(newRunningJob), queue, processedJobs :+ newRunningJob)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob: RunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q enqueue x, processedJobs :+ newRunningJob)
              }
            }
            case (Some(x), Some(_)) if queue.size < sizeOfQueue =>
              (curRunningJob, queue enqueue x, processedJobs)
            case (Some(x), _) =>
              val failedPendingJob = x.start(curTime)
              (curRunningJob, queue, processedJobs :+ FailedJob(x.index))
          }

        loop(nextRunningJob, newRemainingJobs, newQueue, nextStartTime, newProcessedJobs)
      }
    }
    loop(None, jobs, Queue[PendingJob](), 0, Vector[RunningJob]())
  }

  //Parses a single line of input into a job
  private def parseJob(line: String, index: Int): PendingJob = {
    val startAndProcess: Array[Int] = line.split(" ").map(_.toInt)
    PendingJob(index, startAndProcess(0), startAndProcess(1))
  }
}

//a single processing job
trait Job
case class PendingJob(index: Int, arrivalTime: Long, processTime: Long) extends Job {
  def start(curTime: Long) = RunningJob(index, curTime + processTime)
}
abstract class FinishedJob(val index: Int, val endTime: Long) {
  override def toString = endTime.toString
}
case class RunningJob(theIndex: Int, theEndTime: Long) extends FinishedJob(theIndex, theEndTime)
case class FailedJob(theIndex: Int) extends FinishedJob(theIndex, -1)

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

object Solution {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines.toList
    val (firstLine, rest) =
      lines match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, queueSize) =
      firstLine.split(" ") match {
        case Array(x, y) => (x.toInt, y.toInt)
      }

    val jobs = (for {
      line <- rest.zipWithIndex
    } yield parseLine(line)).toList

    val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)
    finishedJobs.foreach(x => print(x.getEndTime + " "))
    println
  }

  def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {
    val queue = Queue[PendingJob]()
    val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]
    val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]

    def queuePendingJobs(curTime: Long) = {
      if(!remainingJobs.isEmpty)println(remainingJobs.head.arrivalTime)
      while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {
        val head = remainingJobs.remove(0)
        if (queue.size == queueSize) {
          finishedJobs += head.fail
        } else {
          queue enqueue head
          finishedJobs += head.run(curTime)
        }
      }
    }

    def getNextRunningJob(curTime: Long): Option[PendingJob] = {
      if (!queue.isEmpty)
        Some(queue.dequeue)
      else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {
        val job = remainingJobs.remove(0)
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else
        None
    }

    def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {
      println("Current time is " + curTime)
      if (queue.isEmpty && remainingJobs.isEmpty) {
        finishedJobs.toVector
      } else if (!queue.isEmpty && remainingJobs.isEmpty) {
        var currentTime = curTime
        while (!queue.isEmpty) {
          val curJob = queue.dequeue
          val runJob = curJob.run(currentTime)
          finishedJobs += runJob
          currentTime = currentTime + curJob.processTime
        }
        finishedJobs.toVector
      } else {
        queuePendingJobs(curTime)

        val f = () => {
          val nextJob = getNextRunningJob(curTime)
          nextJob match {
            case Some(y) => {
              val completeNextJob = y.run(curTime)
              Some(completeNextJob)
            }
            case _ => None
          }
        }
        val nextRunningJob: Option[CompleteJob] =
          curJob match {
            case Some(x) if (x.endTime <= curTime) => f()
            case Some(x) => Some(x)
            case None => f()
          }

        val getNextStartTime: Long =
          nextRunningJob match {
            case Some(x) => x.endTime
            case None    => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1
          }
        loop(nextRunningJob, getNextStartTime)
      }
    }

    loop(None, 0)
  }

  def parseLine(line: Tuple2[String, Int]): PendingJob = {
    line._1.split(" ") match {
      case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)
    }
  }

}

case class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {
  def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)
  def fail: FailedJob = FailedJob(id)
}
trait FinishedJob {
  def getId: Int
  def getEndTime: Long
}
case class CompleteJob(id: Int, endTime: Long) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = endTime
}
case class FailedJob(id: Int) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = -1L
}

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

object Solution {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines.toList
    val (firstLine, rest) =
      lines match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, queueSize) =
      firstLine.split(" ") match {
        case Array(x, y) => (x.toInt, y.toInt)
      }

    val jobs = (for {
      line <- rest.zipWithIndex
    } yield parseLine(line)).toList

    val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)
    finishedJobs.foreach(x => print(x.getEndTime + " "))
    println
  }

  def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {
    val queue = Queue[PendingJob]()
    val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]
    val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]

    def queuePendingJobs(curTime: Long) = {
      while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {
        val head = remainingJobs.remove(0)
        if (queue.size == queueSize) {
          finishedJobs += head.fail
        } else {
          queue enqueue head
          finishedJobs += head.run(curTime)
        }
      }
    }

    def getNextRunningJob(curTime: Long): Option[PendingJob] = {
      if (!queue.isEmpty)
        Some(queue.dequeue)
      else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {
        val job = remainingJobs.remove(0)
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else
        None
    }

    def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {
      if (queue.isEmpty && remainingJobs.isEmpty) {
        finishedJobs.toVector
      } else if (!queue.isEmpty && remainingJobs.isEmpty) {
        var currentTime = curTime
        while (!queue.isEmpty) {
          val curJob = queue.dequeue
          val runJob = curJob.run(currentTime)
          finishedJobs += runJob
          currentTime = currentTime + curJob.processTime
        }
        finishedJobs.toVector
      } else {
        queuePendingJobs(curTime)

        val f = () => {
          val nextJob = getNextRunningJob(curTime)
          nextJob match {
            case Some(y) => {
              val completeNextJob = y.run(curTime)
              Some(completeNextJob)
            }
            case _ => None
          }
        }
        val nextRunningJob: Option[CompleteJob] =
          curJob match {
            case Some(x) if (x.endTime <= curTime) => f()
            case Some(x) => Some(x)
            case None => f()
          }

        val getNextStartTime: Long =
          nextRunningJob match {
            case Some(x) => x.endTime
            case None    => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1
          }
        loop(nextRunningJob, getNextStartTime)
      }
    }

    loop(None, 0)
  }

  def parseLine(line: Tuple2[String, Int]): PendingJob = {
    line._1.split(" ") match {
      case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)
    }
  }

}

case class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {
  def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)
  def fail: FailedJob = FailedJob(id)
}
trait FinishedJob {
  def getId: Int
  def getEndTime: Long
}
case class CompleteJob(id: Int, endTime: Long) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = endTime
}
case class FailedJob(id: Int) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = -1L
}

import scala.collection.immutable.Queue

object Solution {

  def main(args: Array[String]): Unit = {
    val (firstLine, lines) =
      scala.io.Source.stdin.getLines.toList match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, sizeOfQueue) =
      firstLine.split(" ").map(_.toInt) match {
        case Array(x, y) => (x, y)
      }

    val jobs: List[PendingJob] =
      for {
        line <- lines
      } yield parseJob(line)

    processJobs(jobs, numQueries, sizeOfQueue).foreach(x => print(x + " "))
    println
  }

  def processJobs(jobs: List[PendingJob], numQueries: Int, sizeOfQueue: Int): Vector[Int] = {
    def loop(curJob: Option[RunningJob], remainingJobs: List[PendingJob], queue: Queue[PendingJob], curTime: Int, processedJobs: Vector[Int]): Vector[Int] = {
      if (remainingJobs.isEmpty && queue.isEmpty) {
        processedJobs
      } else {
        val (currentlyArrivingJob, newRemainingJobs) =
          remainingJobs match {
            case x::xs if x.arrivalTime == curTime => (Some(x), xs)
            case _ => (None, remainingJobs)
          }

        val curRunningJob: Option[RunningJob] =
          curJob match {
            case Some(x) if x.endTime == curTime => None
            case _ => curJob
          }

        val (nextRunningJob, newQueue, newProcessedJobs) =
          (currentlyArrivingJob, curRunningJob) match {
            case (None, Some(_)) => (curRunningJob, queue, processedJobs)
            case (None, None) => {
              if (queue.isEmpty) {
                (None, queue, processedJobs)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q, processedJobs :+ newRunningJob.endTime)
              }
            }
            case (Some(x), None) => {
              if (queue.isEmpty) {
                val newRunningJob = x.start(curTime)
                (Some(newRunningJob), queue, processedJobs :+ newRunningJob.endTime)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob: RunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q enqueue x, processedJobs :+ newRunningJob.endTime)
              }
            }
            case (Some(x), Some(_)) if queue.size < sizeOfQueue =>
              (curRunningJob, queue enqueue x, processedJobs)
            case _ =>
              (curRunningJob, queue, processedJobs :+ -1)
          }

        loop(nextRunningJob, newRemainingJobs, newQueue, curTime + 1, newProcessedJobs)
      }
    }
    loop(None, jobs, Queue[PendingJob](), 0, Vector[Int]())
  }

  //Parses a single line of input into a job
  private def parseJob(line: String): PendingJob = {
    val startAndProcess: Array[Int] = line.split(" ").map(_.toInt)
    PendingJob(startAndProcess(0), startAndProcess(1))
  }
}

//a single processing job
trait Job
case class PendingJob(arrivalTime: Int, processTime: Int) extends Job {
  def start(curTime: Int) = RunningJob(curTime + processTime)
}
case class RunningJob(endTime: Int) extends Job


In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.

The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers mi, di, pi and ti — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ mi ≤ 12, di ≥ 1, 1 ≤ pi, ti ≤ 100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year.

Print a single number — the minimum jury size.

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)

	val n=in.nextLine.toInt
	var olyms=new Array[Olym](n)
	for(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(" ").map(_.toInt))
	olyms=olyms.sortBy(_.start)
	var hm=collection.mutable.Map[Int,Int]()
	for(o<-olyms)
	{
		o.start until o.end foreach{i=>
			hm(i)=hm.getOrElse(i, 0)+o.p
		}
	}

	out.println(hm.values.max)
	out.close
}

class Olym(input:Array[Int]){
    private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
    val end=months.slice(0,input(0)).sum+input(1)
    val start=end-input(3)
    val p=input(2)

    override def toString="%d:%d:%d".format(start,end,p)

    def isOverlap(o:Olym):Boolean={
        ((start until end toSet) & (o.start until o.end toSet)).size>0
    }
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)
	val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
	val n=in.nextLine.toInt
	var hm=collection.mutable.Map[Int,Int]()

	for(i<-0 until n){
	    val Array(m,d,p,t)=in.nextLine.split(" ").map(_.toInt)
	    val end=months.slice(0,m).sum+d
	    val start=end-t

	    start until end foreach{j=>
	    	hm(j)=hm.getOrElse(j, 0)+p
	    }
	}

	out.println(hm.values.max)
	out.close
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)

	val n=in.nextLine.toInt
	var olyms=new Array[Olym](n)
	for(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(" ").map(_.toInt))
	olyms=olyms.sortBy(_.day)

	var max=0
	var start=0
	var total=0
	for(i<-0 until n)
	{
		var j=0
		while(j<i && !olyms(j).isOverlap(olyms(i)))
		{
			total-=olyms(j).p
			j+=1
		}
		start=j
	    total+=olyms(i).p
	    max=math.max(max,total)
	}

	out.println(max)
	out.close
}
class Olym(input:Array[Int]){
    private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
    val day=months.slice(0,input(0)).sum+input(1)
    val p=input(2)
    val t=input(3)

    override def toString="%d:%d:%d".format(day,p,t)

    def isOverlap(o:Olym):Boolean={
        ((day-t until day toSet) & (o.day-o.t until o.day toSet)).size>0
    }
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)

	val n=in.nextLine.toInt
	var olyms=new Array[Olym](n)
	for(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(" ").map(_.toInt))
	olyms=olyms.sortBy(_.day)

	var max=0
	var start=0
	var total=0
	for(i<-0 until n)
	{
		var j=0
		while(j<i && !olyms(j).isOverlap(olyms(i)))
		{
			total-=olyms(j).p
			j+=1
		}
		start=j
	    total+=olyms(i).p
	    max=math.max(max,total)
	}

	println(max)
}
class Olym(input:Array[Int]){
    private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
    val day=months.slice(0,input(0)).sum+input(1)
    val p=input(2)
    val t=input(3)

    override def toString="%d:%d:%d".format(day,p,t)

    def isOverlap(o:Olym):Boolean={
        ((day-t until day toSet) & (o.day-o.t until o.day toSet)).size>0
    }
}


You're given an array of $$$n$$$ integers between $$$0$$$ and $$$n$$$ inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is $$$[0, 2, 2, 1, 4]$$$, you can choose the second element and replace it by the MEX of the present elements  — $$$3$$$. Array will become $$$[0, 3, 2, 1, 4]$$$.You must make the array non-decreasing, using at most $$$2n$$$ operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array $$$b[1 \ldots n]$$$ is non-decreasing if and only if $$$b_1 \le b_2 \le \ldots \le b_n$$$.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:  The MEX of $$$[2, 2, 1]$$$ is $$$0$$$, because $$$0$$$ does not belong to the array.  The MEX of $$$[3, 1, 0, 1]$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the array, but $$$2$$$ does not.  The MEX of $$$[0, 3, 1, 2]$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the array, but $$$4$$$ does not. It's worth mentioning that the MEX of an array of length $$$n$$$ is always between $$$0$$$ and $$$n$$$ inclusive.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 1000$$$) — length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array. Note that they don't have to be distinct. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$.

For each test case, you must output two lines: The first line must contain a single integer $$$k$$$ ($$$0 \le k \le 2n$$$)  — the number of operations you perform. The second line must contain $$$k$$$ integers $$$x_1, \ldots, x_k$$$ ($$$1 \le x_i \le n$$$), where $$$x_i$$$ is the index chosen for the $$$i$$$-th operation. If there are many solutions, you can find any of them. Please remember that it is not required to minimize $$$k$$$.

NoteIn the first test case, the array is already non-decreasing ($$$2 \le 2 \le 3$$$).Explanation of the second test case (the element modified by each operation is colored in red):   $$$a = [2, 1, 0]$$$ ; the initial MEX is $$$3$$$.  $$$a = [2, 1, \color{red}{3}]$$$ ; the new MEX is $$$0$$$.  $$$a = [\color{red}{0}, 1, 3]$$$ ; the new MEX is $$$2$$$.  The final array is non-decreasing: $$$0 \le 1 \le 3$$$. Explanation of the third test case:   $$$a = [0, 7, 3, 1, 3, 7, 7]$$$ ; the initial MEX is $$$2$$$.  $$$a = [0, \color{red}{2}, 3, 1, 3, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, 1, \color{red}{4}, 7, 7]$$$ ; the new MEX is $$$5$$$.  $$$a = [0, 2, 3, 1, \color{red}{5}, 7, 7]$$$ ; the new MEX is $$$4$$$.  $$$a = [0, 2, 3, \color{red}{4}, 5, 7, 7]$$$ ; the new MEX is $$$1$$$.  The final array is non-decreasing: $$$0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7$$$.

import scala.collection.mutable

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

    def isSorted(as: Array[Int]): Boolean = {
      var i = 1
      while (i < as.length) {
        if (as(i) < as(i - 1)) return false
        i += 1
      }
      true
    }

    def mex(counts: Array[Int]): Int = {
      var i = 0
      while (i < counts.length) {
        if (counts(i) == 0) return i
        i += 1
      }
      i
    }

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)
      val counts = Array.fill(n + 2)(0)
      for (a <- as) counts(a) += 1

      val res = mutable.ArrayBuffer.empty[Int]

      while (!isSorted(as)) {
        val m = mex(counts)
        val pos = if (m > n - 1) {
          var i = n - 1
          while (i > 0 && as(i) == i) {
            i -= 1
          }
          i
        } else m
        counts(as(pos)) -= 1
        counts(m) += 1
        as(pos) = m
        res += (pos + 1)
        //println(as.mkString(" "))
      }

      out.println(res.length)
      out.println(res.mkString(" "))
    }

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


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.

For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.

NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.

object A extends App {

  implicit final class StringOps(private val input: String) extends AnyVal {
    def abBalance: String = {
      require(input.nonEmpty, "The given string should not be empty.")

      input.sliding(2).foldLeft(0) {
        case (count, "ab") => count + 1
        case (count, "ba") => count - 1
        case (count, _)    => count
      } match {
        case 0  => input
        case 1  => s"b${input.tail}"
        case -1 => s"a${input.tail}"
      }
    }
  }

  import InOut._

  val t = nextInt()

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

    out.println(s.abBalance)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
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 pair(var s: Int, var a:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (a == that.a && s == that.s)
                return 0
            if (a > that.s && that.a <= s)
                return 1
            if (a <= that.s && that.a > s)
                return -1
            if (a == that.a) {
                if (s < that.s)
                    return -1
                else
                    return 1
            }
            if (a < that.a)
                return -1
            else
                return 1
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        var s = readString()
        var a = 0
        var b = 0
        for (i <- 0 until s.length - 1) {
            if (s(i) == 'a' && s(i+1) == 'b')
                a += 1
            if (s(i) == 'b' && s(i+1) == 'a')
                b += 1
        }
        if (a != b) {
            if(s(0) == 'a')
                s = 'b' + s.substring(1)
            else
                s = 'a' + s.substring(1)
        }
        writer.println(s)
    }
    writer.flush()
}

object A extends App {

  implicit final class StringOps(private val str: String) extends AnyVal {
    def abBalance: String = {
      require(str.nonEmpty, "The given string should not be empty.")

      val intervals = str.indices.tail.foldLeft((0, 0) :: Nil) {
        case ((p, q) :: intervals, i) if str(i) == str(q) => (p, i) :: intervals
        case (intervals, i)                               => (i, i) :: intervals
      }

      if ((intervals.length - 1) % 2 == 0) str
      else {
        val (fl, fr) = intervals.head
        val (ll, lr) = intervals.last
        val (l, r)   = if (fr - fl < lr - ll) (fl, fr) else (ll, lr)

        val slice = (if (str(l) == 'a') "b" else "a") * (r - l + 1)

        s"${str.slice(0, l)}$slice${str.slice(r + 1, str.length)}"
      }
    }
  }

  import InOut._

  val t = nextInt()

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

    out.println(s.abBalance)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

object A extends App {

  implicit final class StringOps(private val str: String) extends AnyVal {
    def abBalance: String = {
      require(str.nonEmpty, "The given string should not be empty.")

      val intervals = str.indices.tail.foldLeft((0, 0) :: Nil) {
        case ((p, q) :: intervals, i) if str(i) == str(q) => (p, i) :: intervals
        case (intervals, i)                               => (i, i) :: intervals
      }

      if ((intervals.length - 1) % 2 == 0) str
      else {
        val (p, q) = intervals.minBy { case (p, q) => q - p }
        val slice  = (if (str(p) == 'a') "b" else "a") * (q - p + 1)

        s"${str.slice(0, p)}$slice${str.slice(q + 1, str.length)}"
      }
    }
  }

  import InOut._

  val t = nextInt()

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

    out.println(s.abBalance)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}


Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has  groups of three.Help Xenia, find the required partition or else say that it doesn't exist.

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.

If the required partition exists, print  groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Array.ofDim[Int](8)
  in.next().split(' ').foreach {
    i => data(i.toInt) += 1
  }
  val rest = if (data(5) != 0 || data(7) != 0)
    Nil
  else {
    var res = List.empty[(Int, Int, Int)]

    (1 to data(3)).foreach { _ =>
      res ::= (1, 3, 6)
    }
    data(1) -= data(3)
    data(6) -= data(3)
    data(3) = 0
    if (data(1) < 0 || data(6) < 0)
      Nil
    else {
      var count = data(1) + data(2) + data(4) + data(6)
      while (count > 0) {
        val list = List(data(4) -> 4, data(6) -> 6).sorted.tail.map(_._2)
        val d = (1 :: 2 :: list).sorted
        res ::= (d.head, d(1), d.last)
        count -= 3
        d.foreach(i => data(i) -= 1)

        if (d.exists(i => data(i) < 0)) {
          count = -1
          res = Nil
        }
      }
      res
    }
  }
  if (rest.isEmpty)
    println(-1)
  else
    println(rest.map(i => s"${i._1} ${i._2} ${i._3}").mkString("\n"))

}

object A342 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val num = readInts(n)
    val map = cu.Map.empty[Int, Int].withDefaultValue(0)
    num.foreach{n1 => map(n1)+=1}
    if(map(1) == n/3 && Array(5,7).forall(map(_) == 0)) {
      if(map(3) <= map(6)) {
        if(map(2) == map(6)-map(3)+map(4)) {
          for(i <- 0 until map(3)) {
            println(s"1 3 6")
          }
          for(i <- 0 until map(6)-map(3)) {
            println(s"1 2 6")
          }
          for(i <- 0 until map(4)) {
            println(s"1 2 4")
          }
        } else {
          out.println("-1")
        }
      } else {
        out.println("-1")
      }
    } else {
      out.println("-1")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

    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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.immutable.Queue
import scala.util.Random

object P342A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val X = Array.fill(N)(sc.nextInt)

  // Possible groups
  // 1 2 4 => g4
  // 1 2 6 => g62
  // 1 3 6 => g63

  def solve(): Unit = {
    val c = Array.fill(8)(0)
    X foreach { x => c(x) += 1 }

    if (c(5) > 0 ||  c(7) > 0) out.println("-1")
    else {
      val g4 = c(4)
      c(1) -= g4
      c(2) -= g4

      if (c(2) < 0 || c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)
      else {
        for (i <- 0 until g4) out.println("1 2 4")
        for (i <- 0 until c(2)) out.println("1 2 6")
        for (i <- 0 until c(3)) out.println("1 3 6")
      }
    }
  }

  solve
  out.close
}

object B {
  def main(args: Array[String]) {
    var n = readInt()
    var a:Array[Int] = readLine() split(" ") map(_.toInt)
    var cnt = (Range(0, 8) map (x=> a.count(_==x))).toArray;
    f(a, cnt, 1, 2, 4)
    f(a, cnt, 1, 2, 6)
    f(a, cnt, 1, 3, 6)
    println(if ((cnt count(_ > 0)) > 0) -1 else result)
  }

  val result = new StringBuilder();
  def f(a:IndexedSeq[Int], cnt:Array[Int], i1:Int, i2:Int, i3:Int) {

    val m = math.min(cnt(i1), math.min(cnt(i2), cnt(i3)));
    for (i <- 1 to m) result.append("%d %d %d\n".format(i1, i2, i3))
    for (i <- List(i1, i2, i3)) cnt(i) -= m;
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)

    val n7 = map.getOrElse(7, 0)
    val n6 = map.getOrElse(6, 0)
    val n5 = map.getOrElse(5, 0)
    val n4 = map.getOrElse(4, 0)
    var n3 = map.getOrElse(3, 0)
    var n2 = map.getOrElse(2, 0)
    var n1 = map.getOrElse(1, 0)

    var seq = scala.collection.mutable.Seq[String]()

    if (n5 != 0 || n7 != 0) { println("-1"); return }

    if (n6 < n3) { println("-1"); return }
    else {
      for (_ <- 1 to n3) seq ++= Seq("1 3 6")
      n2 -= (n6 - n3)
      n1 -= n6
      if (n2 < 0) { println("-1"); return }
      for (_ <- 1 to (n6 - n3)) seq ++= Seq("1 2 6")
    }

    if (n4 != n2) { println("-1"); return }
    else {
      n1 -= n4
      for (_ <- 1 to n2) seq ++= Seq("1 2 4")
    }

    if (n1 != 0) println("-1")
    else seq.foreach(println)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Array.ofDim[Int](8)
  in.next().split(' ').foreach {
    i => data(i.toInt) += 1
  }
  val rest = if (data(5) != 0 || data(7) != 0)
    Nil
  else {
    var res = List.empty[(Int, Int, Int)]

    (1 to data(3)).foreach { _ =>
      res ::= (1, 3, 6)
    }
    data(1) -= data(3)
    data(6) -= data(3)
    data(3) = 0
    if (data(1) < 0 || data(6) < 0)
      Nil
    else {
      var count = data(1) + data(2) + data(4) + data(6)
      while (count > 0) {
        val list = List(data(1) -> 1, data(4) -> 4, data(6) -> 6).sorted.tail.map(_._2)
        val d = (2 :: list).sorted
        res ::= (d.head, d(1), d.last)
        count -= 3
        d.foreach(i => data(i) -= 1)

        if (d.exists(i => data(i) < 0)) {
          count = -1
          res = Nil
        }
      }
      res
    }
  }
  if (rest.isEmpty)
    println(-1)
  else
    println(rest.map(i => s"${i._1} ${i._2} ${i._3}").mkString("\n"))

}

object A342 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val num = readInts(n)
    val map = cu.Map.empty[Int, Int].withDefaultValue(0)
    num.foreach{n1 => map(n1)+=1}
    if(map(1) == n/3) {
      if(map(3) <= map(6)) {
        if(map(2) == map(6)-map(3)+map(4)) {
          for(i <- 0 until map(3)) {
            println(s"1 3 6")
          }
          for(i <- 0 until map(6)-map(3)) {
            println(s"1 2 6")
          }
          for(i <- 0 until map(4)) {
            println(s"1 2 4")
          }
        } else {
          out.println("-1")
        }
      } else {
        out.println("-1")
      }
    } else {
      out.println("-1")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

    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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.immutable.Queue
import scala.util.Random

object P342A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val X = Array.fill(N)(sc.nextInt)

  // Possible groups
  // 1 2 4 => g4
  // 1 2 6 => g62
  // 1 3 6 => g63

  def solve(): Unit = {
    val c = Array.fill(8)(0)
    X foreach { x => c(x) += 1 }

    if (c(5) * c(7) > 0) out.println(-1)
    else {
      val g4 = c(4)
      c(1) -= g4
      c(2) -= g4

      if (c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)
      else {
        for (i <- 0 until g4) out.println("1 2 4")
        for (i <- 0 until c(2)) out.println("1 2 6")
        for (i <- 0 until c(3)) out.println("1 3 5")
      }
    }
  }

  solve
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.immutable.Queue
import scala.util.Random

object P342A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val X = Array.fill(N)(sc.nextInt)

  // Possible groups
  // 1 2 4 => g4
  // 1 2 6 => g62
  // 1 3 6 => g63

  def solve(): Unit = {
    val c = Array.fill(8)(0)
    X foreach { x => c(x) += 1 }

    if (c(5) * c(7) > 0) out.println(-1)
    else {
      val g4 = c(4)
      c(1) -= g4
      c(2) -= g4

      if (c(2) < 0 || c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)
      else {
        for (i <- 0 until g4) out.println("1 2 4")
        for (i <- 0 until c(2)) out.println("1 2 6")
        for (i <- 0 until c(3)) out.println("1 3 6")
      }
    }
  }

  solve
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.immutable.Queue
import scala.util.Random

object P342A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val X = Array.fill(N)(sc.nextInt)

  // Possible groups
  // 1 2 4 => g4
  // 1 2 6 => g62
  // 1 3 6 => g63

  def solve(): Unit = {
    val c = Array.fill(8)(0)
    X foreach { x => c(x) += 1 }

    if (c(5) * c(7) > 0) out.println(-1)
    else {
      val g4 = c(4)
      c(1) -= g4
      c(2) -= g4

      if (c(2) < 0 || c(1) != c(6) || c(2) + c(3) != c(6)) out.println(-1)
      else {
        for (i <- 0 until g4) out.println("1 2 4")
        for (i <- 0 until c(2)) out.println("1 2 6")
        for (i <- 0 until c(3)) out.println("1 3 5")
      }
    }
  }

  solve
  out.close
}

object B {
  def main(args: Array[String]) {
    var n = readInt()
    var a:Array[Int] = readLine() split(" ") map(_.toInt)
    var cnt = (Range(0, 7) map (x=> a.count(_==x))).toArray;
    f(a, cnt, 1, 2, 4)
    f(a, cnt, 1, 2, 6)
    f(a, cnt, 1, 3, 6)
    println(if ((cnt count(_ > 0)) > 0) -1 else result)
  }

  val result = new StringBuilder();
  def f(a:IndexedSeq[Int], cnt:Array[Int], i1:Int, i2:Int, i3:Int) {

    val m = math.min(cnt(i1), math.min(cnt(i2), cnt(i3)));
    for (i <- 1 to m) result.append("%d %d %d\n".format(i1, i2, i3))
    for (i <- List(i1, i2, i3)) cnt(i) -= m;
  }
}

object A {
  var b = false;
  def main(args: Array[String]) {
    var n = readInt()
    var a:Array[Int] = readLine() split(" ") map(_.toInt)
    var cnt = (Range(0, 7) map (x=> a.count(_==x))).toArray;
    f(a, cnt, 1, 2, 4)
    f(a, cnt, 1, 2, 6)
    f(a, cnt, 1, 3, 6)
    if (!b) println(-1)

  }

  def f(a:IndexedSeq[Int], cnt:Array[Int], i1:Int, i2:Int, i3:Int) {
    val m = math.min(cnt(i1), math.min(cnt(i2), cnt(i3)));
    for (i <- 1 to m) { printf("%d %d %d\n", i1, i2, i3); b = true }
    for (i <- List(i1, i2, i3)) cnt(i) -= m;
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)

    val n6 = map.getOrElse(6, 0)
    val n5 = map.getOrElse(5, 0)
    val n4 = map.getOrElse(4, 0)
    var n3 = map.getOrElse(3, 0)
    var n2 = map.getOrElse(2, 0)
    var n1 = map.getOrElse(1, 0)

    var seq = scala.collection.mutable.Seq[String]()

    if (n5 != 0) { println("-1"); return }

    if (n6 < n3) { println("-1"); return }
    else {
      for (_ <- 1 to n3) seq ++= Seq("1 3 6")
      n2 -= (n6 - n3)
      n1 -= n6
      if (n2 < 0) { println("-1"); return }
      for (_ <- 1 to (n6 - n3)) seq ++= Seq("1 2 6")
    }

    if (n4 != n2) { println("-1"); return }
    else {
      n1 -= n4
      for (_ <- 1 to n2) seq ++= Seq("1 2 4")
    }

    if (n1 != 0) println("-1")
    else seq.foreach(println)
  }
}


Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c — one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below:  Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.When rhombi are compared, the order of intersections b and d doesn't matter.

The first line of the input contains a pair of integers n, m (1 ≤ n ≤ 3000, 0 ≤ m ≤ 30000) — the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi) — the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one.

Print the required number of "damn rhombi".

import scala.collection.mutable.ArrayBuilder

object P2775D extends App {

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

  val Array(n, m) = readInts(2)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
  }

  val adj = adjBuilders.map(_.result)

  val cnts = Array.fill(n, n)(0)

  for (u <- 0 until n)
    for (v <- adj(u))
      for (w <- adj(v))
        if (w != u) cnts(w)(u) += 1

  var sum = 0L

  for (u <- 0 until n)
    for (c <- cnts(u))
      if (c > 1) sum += c * (c - 1) / 2

  println(sum)
}

import scala.collection.mutable.ArrayBuilder

object P2775D extends App {

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

  val Array(n, m) = readInts(2)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
  }

  val adj = adjBuilders.map(_.result)

  val cnts = Array.fill(n, n)(0)

  for {
    u <- 0 until n
    v <- adj(u)
    w <- adj(v)
    if w != u
  } cnts(w)(u) += 1

  var sum = 0L

  for {
    u <- 0 until n
    c <- cnts(u)
  } sum += c * (c - 1) / 2

  println(sum)
}

import scala.collection.mutable.ArrayBuilder

object P2775D extends App {

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

  val Array(n, m) = readInts(2)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
  }

  val adj = adjBuilders.map(_.result)

  val cnts = Array.fill(n, n)(0)

  for {
    u <- 0 until n
    v <- adj(u)
    w <- adj(v)
    if w != u
  } cnts(w)(u) += 1

  var sum = 0L

  for {
    u <- 0 until n
    c <- cnts(u)
    if c > 1
  } sum += c * (c - 1) / 2

  println(sum)
}