Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai (1 ≤ ai ≤ 106) — the values of the array elements.

In a single line print a single integer — the maximum number of points Artem can get.

import java.util.InputMismatchException
import java.io.InputStream
import scala.collection

/**
 * Created by hama_du on 2014/06/21.
 */
object ProblemC extends App {
  /**
   * fast IO
   */
  class InputReader(stream: InputStream) {
    val buf = new Array[Byte](1024)
    var curChar = 0
    var numChars = 0

    def next(): Int = {
      if (numChars == -1)
        throw new InputMismatchException();
      if (curChar >= numChars) {
        curChar = 0;
        numChars = stream.read(buf);
        if (numChars <= 0) {
          -1;
        }
      }
      val res = buf(curChar)
      curChar += 1
      res
    }

    def nextLong(): Long = {
      var c = next()
      while (isSpaceChar(c)) {
        c = next()
      }
      var sgn = 1
      if (c == '-') {
        sgn = -1
        c = next()
      }
      var res = 0L
      do {
        if (c < '0' || c > '9')
          throw new InputMismatchException()
        res *= 10
        res += c - '0'
        c = next()
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt(): Int = {
      nextLong.toInt
    }

    def isSpaceChar(c: Int) = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
  }

  def solve(a: Array[(Long,Int)]): Long = {
    val n = a.length
    if (n <= 2) {
      return 0
    }

    val done = new Array[Boolean](n)
    val stack = new collection.mutable.Stack[(Long,Int)]()
    val score = a.foldLeft(0L)((score, topWithIndex) => {
      val (top,_) = topWithIndex
      var nextScore = score
      while (stack.size >= 2 && stack(1)._1 >= stack(0)._1 && stack(0)._1 <= top) {
        nextScore += Math.min(top, stack(1)._1)
        val removed = stack.pop()
        done(removed._2) = true
      }
      stack.push(topWithIndex)
      nextScore
    })
    score + a.filterNot(ai => done(ai._2)).map(ai => ai._1).sorted.dropRight(2).sum
  }

  val in = new InputReader(System.in)
  val n = in.nextInt()
  val a = (0 until n).map(_ => in.nextLong()).toArray.zipWithIndex
  println(solve(a))
}

import java.util.InputMismatchException
import java.io.InputStream
import scala.collection

/**
 * Created by hama_du on 2014/06/21.
 */
object ProblemC extends App {
  /**
   * fast IO
   */
  class InputReader(stream: InputStream) {
    val buf = new Array[Byte](1024)
    var curChar = 0
    var numChars = 0

    def next(): Int = {
      if (numChars == -1)
        throw new InputMismatchException();
      if (curChar >= numChars) {
        curChar = 0;
        numChars = stream.read(buf);
        if (numChars <= 0) {
          -1;
        }
      }
      val res = buf(curChar)
      curChar += 1
      res
    }

    def nextLong(): Long = {
      var c = next()
      while (isSpaceChar(c)) {
        c = next()
      }
      var sgn = 1
      if (c == '-') {
        sgn = -1
        c = next()
      }
      var res = 0L
      do {
        if (c < '0' || c > '9')
          throw new InputMismatchException()
        res *= 10
        res += c - '0'
        c = next()
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt(): Int = {
      nextLong.toInt
    }

    def isSpaceChar(c: Int) = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
  }

  /**
   * solution
   */
  def solve(a: Array[Long]): Long = {
    val n = a.length
    if (n <= 2) {
      return 0
    }

    val stack = new collection.mutable.Stack[Long]()
    val score = a.foldLeft(0L)((score, top) => {
      var nextScore = score
      while (stack.size >= 2 && stack(1) >= stack(0) && stack(0) <= top) {
        nextScore += Math.min(top, stack(1))
        stack.pop()
      }
      stack.push(top)
      nextScore
    })
    score + stack.toArray.sorted.dropRight(2).sum
  }

  val in = new InputReader(System.in)
  val n = in.nextInt()
  val a = (0 until n).map(_ => in.nextLong()).toArray
  println(solve(a))
}

import java.util.InputMismatchException
import java.io.InputStream

/**
 * Created by hama_du on 2014/06/21.
 */
object ProblemC extends App {
  /**
   * fast IO
   */
  class InputReader(stream: InputStream) {
    val buf = new Array[Byte](1024)
    var curChar = 0
    var numChars = 0

    def next(): Int = {
      if (numChars == -1)
        throw new InputMismatchException();
      if (curChar >= numChars) {
        curChar = 0;
        numChars = stream.read(buf);
        if (numChars <= 0) {
          -1;
        }
      }
      val res = buf(curChar)
      curChar += 1
      res
    }

    def nextLong(): Long = {
      var c = next()
      while (isSpaceChar(c)) {
        c = next()
      }
      var sgn = 1
      if (c == '-') {
        sgn = -1
        c = next()
      }
      var res = 0L
      do {
        if (c < '0' || c > '9')
          throw new InputMismatchException()
        res *= 10
        res += c - '0'
        c = next()
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt(): Int = {
      nextLong.toInt
    }

    def isSpaceChar(c: Int) = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
  }

  def solve(a: Array[(Long,Int)]): Long = {
    val n = a.length
    if (n <= 2) {
      return 0
    }

    val done = new Array[Boolean](n)
    val score = a.foldLeft((-2L, -1L, 0L))((lcs, rightWithIndex) => {
      val (left, center, score) = lcs
      val (right,index) = rightWithIndex
      if (left >= center && center <= right) {
        done(index-1) = true
        (left, right, score + Math.min(left, right))
      } else {
        (center, right, score)
      }
    })._3
    score + a.filterNot(ai => done(ai._2)).map(ai => ai._1).sorted.dropRight(2).sum
  }

  val in = new InputReader(System.in)
  val n = in.nextInt()
  val a = (0 until n).map(_ => in.nextLong()).toArray.zipWithIndex
  println(solve(a))
}


Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure:  Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.

The first line of input contains an integer n (1 ≤ n ≤ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 ≤ ki ≤ 109, 1 ≤ ai ≤ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.

Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2p.

NotePicture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.In the second test case, we can put all four small boxes into a box with side length 2.

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(x => x(0)).map(p => (p(0), p(1)))
  def cnt(k: Int, num: Int) =
    if (k >= 16) (if (num != 0) 1 else 0) else (num - 1 + (1 << (2 * k))) >> (2 * k)
  var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))
  while (k != 1) {
    ans += 1
    k = (k + 3) >> 2
  }
  println(List(ans, input(n-1)._1 + 1).max)
}

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    var best = 0
    for (_ <- 1 to n) {
      val Array(k, a) = readLine().split(" ").map(_.toInt)
      var need = k + 1;
      var c:Long = 4
      while (a > c) {
        need = need + 1
        c *= 4
      }
      if (need > best) {
        best = need
      }
    }
    println(best)
  }
}

import collection.mutable.Queue

object test6 extends App {
    val getCount=(count:Double, layer:Int)=>(count/math.pow(4,layer)).ceil toInt

    //println(getCount(17,2))

    val n=readLine.toInt
    var arr=(for(i<-0 until n) yield readLine.split(" ").map(_.toInt) toArray) sortBy {a=>a(0)}

    var count=arr(0)(1)
    for(i<- 1 until arr.length){
        count=math.max(arr(i)(1),getCount(count, arr(i)(0)-arr(i-1)(0)))
    }

    var i=arr.last.head
    while(count>1) {count=getCount(count,1);i+=1}

    println(math.max(i,arr.last.head+1))
}

object test6 extends App {
    val getCount=(count:Double, layer:Int)=>(count/math.pow(4,layer)).ceil toInt

    val n=readLine.toInt
    var arr=(for(i<-0 until n) yield readLine.split(" ").map(_.toInt) toArray) sortBy {a=>a(0)}

    var count=arr(0)(1)
    for(i<- 1 until arr.length){
        count=math.max(arr(i)(1),getCount(count, arr(i)(0)-arr(i-1)(0)))
    }

    val ans=arr.last.head+((math.log(count)/math.log(4)).ceil toInt)
    println(math.max(ans,arr.last.head+1))
}

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))
  def cnt(k: Int, n: Int) = (n - 1 + (1 << (2 * k))) >> (2 * k)
  var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))
  while (k != 1) {
    ans += 1
    k = (k + 3) >> 2
  }
  println( if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)
}

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))
  def cnt(k: Int, n: Int) = (n - 1 + (1 << (2 * k))) >> (2 * k)
  var (ans, k) = input.reduceLeft((l, r) => (r._1, r._2 + cnt(r._1 - l._1, l._2)))
  while (k != 1) {
    ans += 1
    k = (k + 3) >> 2
  }
  println( if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)
}

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))
  def cnt(k: Int, n: Int) = (n - 1 + (1 << (2 * k))) >> (2 * k)
  var (k, ans) = input.reduceLeft((l, r) => (r._1, r._2 + cnt(r._1 - l._1, l._2)))
  while (k != 1) {
    ans += 1
    k = (k + 3) >> 2
  }
  println(ans)
}

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(p => p(1)).map(p => (p(0), p(1)))
  def cnt(k: Int, n: Int): Int = (n - 1 + (1 << (2 * k))) >> (2 * k)
  var (ans, k) = input.reduceLeft((l, r) => (r._1, r._2 + cnt(r._1 - l._1, l._2)))
  while (k != 1) {
    ans += 1
    k = (k + 3) / 4
  }
  println(ans)
}

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(x => x(0)).map(p => (p(0), p(1)))
  def cnt(k: Int, num: Int) = (num - 1 + (1 << (2 * k))) >> (2 * k)
  var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))
  while (k != 1) {
    ans += 1
    k = (k + 3) >> 2
  }
  println(if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)
}

object cf165c extends App {
  val n = readLine.toInt
  val input = (1 to n).map(n => readLine.split(' ').map(_.toInt)).sortBy(x => x(0)).map(p => (p(0), p(1)))
  def cnt(k: Int, num: Int) =
    if (k >= 16) (if (num != 0) 1 else 0) else (num - 1 + (1 << (2 * k))) >> (2 * k)
  var (ans, k) = input.reduceLeft((l, r) => (r._1, List(r._2, cnt(r._1 - l._1, l._2)).max))
  while (k != 1) {
    ans += 1
    k = (k + 3) >> 2
  }
  println(if (input.length == 1 && input(0)._2 == 1) input(0)._1 + 1 else ans)
}

import collection.mutable.Queue

object test6 extends App {
    val n=readLine.toInt
    var arr=(for(i<-0 until n) yield readLine.split(" ").map(_.toInt) toArray) sortBy {a=>a(0)}

    //for(i<-0 until n) println(arr(i).mkString(","))
    val getCount=(count:Int)=>count/4 + (if(count%4==0) 0 else 1)
    var count=0
    var j=0
    for(i<-0 to arr.last.head){
        if(arr(j)(0)==i){
            count=math.max(getCount(count), arr(j).last)
            j+=1
        }
        else count=getCount(count)
    }

    var i=arr.last.head
    while(count>1) {count=getCount(count);i+=1}
    println(i)
}

import collection.mutable.Queue

object test6 extends App {
    val n=readLine.toInt
    var arr=(for(i<-0 until n) yield readLine.split(" ").map(_.toInt) toArray) sortBy {a=>a(0)}

    //for(i<-0 until n) println(arr(i).mkString(","))
    val getCount=(count:Int)=>count/4 + (if(count%4==0) 0 else 1)
    var count=0
    var j=0
    for(i<-0 to arr.last.head){
        if(arr(j)(0)==i){
            count=math.max(getCount(count), arr(j).last)
            j+=1
        }
        else count=getCount(count)
    }

    var i=arr.last.head
    while(count>1) {count=getCount(count);i+=1}

    println(if(i==arr.last.head) i+1 else 1)
}

object test6 extends App {
    val getCount=(count:Double, layer:Int)=>(count/math.pow(4,layer)).ceil toInt

    val n=readLine.toInt
    var arr=(for(i<-0 until n) yield readLine.split(" ").map(_.toInt) toArray) sortBy {a=>a(0)}

    var count=arr(0)(1)
    for(i<- 1 until arr.length){
        count=math.max(arr(i)(1),getCount(count, arr(i)(0)-arr(i-1)(0)))
    }

    val ans=arr.last.head+(math.log(count)/math.log(4) toInt)
    println(math.max(ans,arr.last.head+1))
}


According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.

The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.

Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.

object P032A extends App {
  def upper(a: Array[Int], pos: Int, h: Int):Int = {
    var i = pos
    val b = a(i) + h
    var j = a.length - 1
    if (a(j) <= b) return j;
    while (j > i + 1) {
      val mid = (i + j) / 2
      if (a(mid) <= b) i = mid
      else             j = mid
    }
    return i
  }
  def lower(a: Array[Int], pos:Int, h: Int):Int = {
    var i = 0
    var j = pos
    val b = a(j) - h
    if (a(i) >= b) return i
    while (j > i + 1) {
      val mid = (i + j) / 2
      if (a(mid) < b) i = mid
      else            j = mid
    }
    return j;
  }

  val param = readLine.split(' ').map(_.toInt)
  val a = readLine.split(' ').map(_.toInt).sorted
  var result = 0
  for (i <- 0 to param(0)-1) {
    result += upper(a, i, param(1)) - lower(a, i, param(1))
  }
  print(result)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)

  println(line.indices.foldLeft(0) {
    case (acc, i) => acc + line.indices.count(j => i != j && Math.abs(line(i) - line(j)) <= d)
    })
}

object A32 {
  import IO._
  import collection.{mutable => cu}
  def main(args: Array[String]): Unit = {
    val Array(n, d) = readInts(2)
    val num = readLongs(n).sorted
    var res = 0
    for(i <- 0 until n; j <- i+1 until n) {
      if(num(j)-num(i) <= d)
        res += 1
    }
    out.println(2*res)
    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 scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, d) = readLine.split(" ").map(_.toInt);
    var arr = readLine.split(" ").map(_.toInt);
    var result = 0;
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        if (i != j) {
    	  if (math.abs(arr(i) - arr(j)) <= d) {
    	    result += 1;
    	  }
        }
      }
    }
    println(result);
  }

}


Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are $$$n$$$ flights from A to B, they depart at time moments $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ and arrive at B $$$t_a$$$ moments later.There are $$$m$$$ flights from B to C, they depart at time moments $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ and arrive at C $$$t_b$$$ moments later.The connection time is negligible, so one can use the $$$i$$$-th flight from A to B and the $$$j$$$-th flight from B to C if and only if $$$b_j \ge a_i + t_a$$$.You can cancel at most $$$k$$$ flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $$$k$$$ flights. If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$.

The first line contains five integers $$$n$$$, $$$m$$$, $$$t_a$$$, $$$t_b$$$ and $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le n + m$$$, $$$1 \le t_a, t_b \le 10^9$$$) — the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively. The second line contains $$$n$$$ distinct integers in increasing order $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ ($$$1 \le a_1 < a_2 < \ldots < a_n \le 10^9$$$) — the times the flights from A to B depart. The third line contains $$$m$$$ distinct integers in increasing order $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ ($$$1 \le b_1 < b_2 < \ldots < b_m \le 10^9$$$) — the times the flights from B to C depart.

If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$. Otherwise print the earliest time Arkady can arrive at C if you cancel $$$k$$$ flights in such a way that maximizes this time.

NoteConsider the first example. The flights from A to B depart at time moments $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ and arrive at B at time moments $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, respectively. The flights from B to C depart at time moments $$$1$$$, $$$2$$$, $$$3$$$, $$$9$$$, and $$$10$$$ and arrive at C at time moments $$$2$$$, $$$3$$$, $$$4$$$, $$$10$$$, $$$11$$$, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment $$$4$$$, and take the last flight from B to C arriving at C at time moment $$$11$$$.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C.

object B extends App {

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

  val Array(n, m, ta, tb, k) = readInts(5)
  val as = readLongs(n)
  val bs = readLongs(m)

  if (n <= k || m <= k) {
    println(-1)
  } else {
    var j = 0
    var max = 0L
    for (i <- 0 to k) {
      val at = as(i) + ta
      while (j < m && at > bs(j)) j += 1
      val j2 = j + (k - i)
      if (j2 >= m) {
        println(-1)
        System.exit(0)
      } else {
        val m = bs(j2) + tb
        if (m > max) max = m
      }
    }
    println(max)
  }
}


Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.

First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph. Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.

Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge. The edges are numbered from 1 to m in order of their appearing in input.

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  //new Thread(null, new Main, "", 32 * 1024 * 1024).start()

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      ancestorsBuilder.sizeHint(ancestors(prev).length + 1)
      maxWBuilder.sizeHint(ancestors(prev).length + 1)
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val res = Array.ofDim[Long](m)

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) res(i) = mstWeight
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

  out.println(res.mkString("\n"))
  out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      //ancestorsBuilder.sizeHint(ancestors(prev).length + 1)
      //maxWBuilder.sizeHint(ancestors(prev).length + 1)
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val res = Array.ofDim[Long](m)

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) res(i) = mstWeight
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

  out.println(res.mkString("\n"))
  out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) out.println(mstWeight)
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      out.println(mstWeight - maxW + edge.w)
    }
  }

  out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val res = Array.ofDim[Long](m)

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) res(i) = mstWeight
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

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

import scala.collection.mutable.ArrayBuilder
import scala.util.Sorting
import scala.collection.mutable.BitSet

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size){ 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

  @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.ofRef[Edge] }

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    adjBuilders(edge.u) += edge
    adjBuilders(edge.v) += edge.reverse
  }

  val adjs = adjBuilders.map(_.result)

  val res = Array.ofDim[Long](m)
  val onMst = new BitSet(m)
  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Long]](n)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofLong

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max: Long = w
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = max max maxWs(prev)(i)
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    for (e <- adjs(u)) {
      if (e.v != parent && onMst(e.id)) dfs(e.v, u, depth + 1, e.w)
    }
  }

  def levelAncestor(_v: Int, depth: Int): (Int, Long)  = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0L
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = maxW max maxWs(v)(i)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): (Int, Long) = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) (v, maxW)
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = maxW max maxWs(u)(i) max maxWs(v)(i)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      (ancestors(v)(0), maxW)
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)

  for (edge <- edges.sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
    }
  }

  dfs(0, -1, 0, 0) // prepare

  for (edge <- edges) {
    if (onMst(edge.id)) res(edge.id) = mstWeight
    else {
      val (_, maxW) = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

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


You are given $$$n$$$ pairs of integers $$$(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)$$$. All of the integers in the pairs are distinct and are in the range from $$$1$$$ to $$$2 \cdot n$$$ inclusive.Let's call a sequence of integers $$$x_1, x_2, \ldots, x_{2k}$$$ good if either   $$$x_1 < x_2 > x_3 < \ldots < x_{2k-2} > x_{2k-1} < x_{2k}$$$, or  $$$x_1 > x_2 < x_3 > \ldots > x_{2k-2} < x_{2k-1} > x_{2k}$$$. You need to choose a subset of distinct indices $$$i_1, i_2, \ldots, i_t$$$ and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be $$$a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \ldots, a_{i_t}, b_{i_t}$$$), this sequence is good.What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence $$$i_1, i_2, \ldots, i_t$$$.

The first line contains single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$) — the number of pairs. Each of the next $$$n$$$ lines contain two numbers — $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 2 \cdot n$$$) — the elements of the pairs. It is guaranteed that all integers in the pairs are distinct, that is, every integer from $$$1$$$ to $$$2 \cdot n$$$ is mentioned exactly once.

In the first line print a single integer $$$t$$$ — the number of pairs in the answer. Then print $$$t$$$ distinct integers $$$i_1, i_2, \ldots, i_t$$$ — the indexes of pairs in the corresponding order.

NoteThe final sequence in the first example is $$$1 < 7 > 3 < 5 > 2 < 10$$$.The final sequence in the second example is $$$6 > 1 < 3 > 2 < 5 > 4$$$.

object D extends App {

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

  val Array(n) = readInts(1)
  case class P(a: Int, b: Int, id: Int)

  val ps = Array.tabulate(n) { id =>
    val Array(a, b) = readInts(2)
    P(a, b, id + 1)
  }

  val (pos, neg) = ps.partition(p => p.a > p.b)

  val res = if (pos.length > neg.length) pos.sortBy(_.a).map(_.id) else neg.sortBy(-_.a).map(_.id)

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

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

  Console.flush
}

object D extends App {

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

  val Array(n) = readInts(1)
  case class P(a: Int, b: Int, id: Int)

  def lisLen(as: Array[P]): Array[Int] = {

    val minByLen = Array.fill(as.size) {
      0
    }
    var i, len = 0

    while (i < as.size) {

      var lo = 0
      var hi = len - 1

      while (lo <= hi) {
        val mid = (lo + hi) >> 1
        if (as(minByLen(mid)).b < as(i).a) lo = mid + 1
        else hi = mid - 1
      }

      minByLen(lo) = i
      if (lo == len) len += 1

      i += 1
    }

    minByLen.take(len)
  }

  val ps = Array.tabulate(n) { id =>
    val Array(a, b) = readInts(2)
    P(a, b, id + 1)
  }

  val (_pos, _neg) = ps.partition(p => p.a > p.b)
  val pos = _pos.sortBy(_.a)
  val neg = _neg.map(p => P(-p.a, -p.b, p.id)).sortBy(_.a) //reverse???

  val lis1 = lisLen(pos)
  val lis2 = lisLen(neg)
//println(pos.mkString(" "))
//  println(neg.mkString(" "))
  val res = if (lis1.length > lis2.length) lis1.map(pos(_).id) else lis2.reverse.map(neg(_).id)

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

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

  Console.flush
}

object D extends App {

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

  val Array(n) = readInts(1)
  case class P(a: Int, b: Int, id: Int)

  def lisLen(as: Array[P]): Array[Int] = {

    val minByLen = Array.fill(as.size) {
      0
    }
    var i, len = 0

    while (i < as.size) {

      var lo = 0
      var hi = len - 1

      while (lo <= hi) {
        val mid = (lo + hi) >> 1
        if (as(minByLen(mid)).b < as(i).a) lo = mid + 1
        else hi = mid - 1
      }

      minByLen(lo) = i
      if (lo == len) len += 1

      i += 1
    }

    minByLen.take(len)
  }

  val ps = Array.tabulate(n) { id =>
    val Array(a, b) = readInts(2)
    P(a, b, id + 1)
  }

  val (_pos, _neg) = ps.partition(p => p.a > p.b)
  val pos = _pos.sortBy(- _.b)
  val neg = _neg.map(p => P(-p.a, -p.b, p.id)).sortBy(- _.b) //reverse???

  val lis1 = lisLen(pos)
  val lis2 = lisLen(neg)
//println(pos.mkString(" "))
//  println(neg.mkString(" "))
  val res = if (lis1.length > lis2.length) lis1.map(pos(_).id) else lis2.reverse.map(neg(_).id)

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

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

  Console.flush
}

object D extends App {

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

  val Array(n) = readInts(1)
  case class P(a: Int, b: Int, id: Int)

  def lisLen(as: Array[P]): Array[Int] = {

    val minByLen = Array.fill(as.size) {
      0
    }
    var i, len = 0

    while (i < as.size) {

      var lo = 0
      var hi = len - 1

      while (lo <= hi) {
        val mid = (lo + hi) >> 1
        if (as(minByLen(mid)).b < as(i).a) lo = mid + 1
        else hi = mid - 1
      }

      minByLen(lo) = i
      if (lo == len) len += 1

      i += 1
    }

    minByLen.take(len)
  }

  val ps = Array.tabulate(n) { id =>
    val Array(a, b) = readInts(2)
    P(a, b, id + 1)
  }

  val (_pos, _neg) = ps.partition(p => p.a > p.b)
  val pos = _pos.sortBy(_.b)
  val neg = _neg.map(p => P(-p.a, -p.b, p.id)).sortBy(_.b) //reverse???

  val lis1 = lisLen(pos)
  val lis2 = lisLen(neg)
//println(pos.mkString(" "))
//  println(neg.mkString(" "))
  val res = if (lis1.length > lis2.length) lis1.map(pos(_).id) else lis2.reverse.map(neg(_).id)

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

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

  Console.flush
}


The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:  The query to swap two table rows;  The query to swap two table columns;  The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.

The first line contains three space-separated integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 500000) — the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each — the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≤ p ≤ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers.   If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≤ x, y ≤ m, x ≠ y);  If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≤ x, y ≤ n, x ≠ y);  If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≤ x ≤ n, 1 ≤ y ≤ m).  The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns — from left to right from 1 to m.

For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.

NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map(_ => in.next().split(' ').map(_.toInt))
  val lines = Array.range(0, n)
  val columns = Array.range(0, m)
  var resultCount = 0
  val query = (1 to k).map{ _ =>
    val Array(t, a, b) = in.next().split(' ')
    val head = t.head
    if (head == 'g')
      resultCount += 1
    (t.head, a.toInt - 1, b.toInt - 1)
  }
  val result = Array.ofDim[Int](resultCount)
  var i = 0
  query.foreach {
    case ('c', a, b) =>
      val tmp = columns(a)
      columns(a) = columns(b)
      columns(b) = tmp
    case ('r', a, b) =>
      val tmp = lines(a)
      lines(a) = lines(b)
      lines(b) = tmp
    case ('g', a, b) =>
      result(i) = data(lines(a))(columns(b))
      i += 1
  }
  println(result.mkString("\n"))
}


You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.The decoding of the lever description is given below.  If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.  If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.  If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.

The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar. To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.

Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.

NoteAs you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.The pictures to the examples:

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var str = in.next().split('^')
  val left = str.head.reverse.zipWithIndex.foldLeft(0l){
    case(sum, ('=', index)) => sum
    case(sum, (el, index)) => sum + 1l * el.asDigit * (index + 1)
  }
  val right = str.last.zipWithIndex.foldLeft(0l){
    case(sum, ('=', index)) => sum
    case(sum, (el, index)) => sum + 1l * el.asDigit * (index + 1)
  }
  if (left == right)
    println("balance")
  else if (left > right)
    println("left")
  else
    println("right")
}

object A376 {

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

  def main(args: Array[String]): Unit = {
    var Array(left, right) = read.split('^')
    left = left.reverse
    var lw = 0L
    for(i <- 0 until left.length if left(i).isDigit) {
      lw += (i+1)*(left(i)-'0')
    }
    var rw = 0L
    for(i <- 0 until right.length if right(i).isDigit) {
      rw += (i+1)*(right(i)-'0')
    }
    if(rw == lw) {
      println("balance")
    } else if (rw > lw) {
      println("right")
    } else {
      println("left")
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @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.util.Random

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

  type Lever = Array[Char]

  val lever: Lever = sc.nextLine.toArray
  val N: Int = lever.length

  def solve(): String = {

    @inline
    def w(c: Char): Long = {
      if (c == '=') 0l
      else (c - '0').toLong
    }

    val pivot: Int = {
      var i = 0
      while (lever(i) != '^') i += 1
      i
    }

    val lhs: Long = {
      var i = pivot - 1
      var res = 0l
      while (i >= 0) {
        res += (pivot - i) * w(lever(i))
        i -= 1
      }
      res
    }

    val rhs: Long = {
      var i = pivot + 1
      var res = 0l
      while (i < N) {
        res += (i - pivot) * w(lever(i))
        i += 1
      }
      res
    }

    if (lhs > rhs) "left"
    else if (lhs < rhs) "right"
    else "balance"
  }

  out.println(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.util.Random

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

  type Lever = Array[Char]
  val lever: Lever = sc.nextLine.toArray

  def solve(): String = {
    val pivot: Int = lever.indexOf('^')
    val lhs = lever.slice(0, pivot).reverse
    val rhs = lever.slice(pivot + 1, lever.length)

    def moment(l: Lever): Long = {

      def w(c: Char): Long = if (c == '=') 0l
                             else (c - '0').toLong

      var res = 0l
      0 until l.size foreach { i => res += (i + 1) * w(l(i)) }
      res
    }

    val rm = moment(rhs)
    val lm = moment(lhs)

    if (lm > rm) "left"
    else if (lm < rm) "right"
    else "balance"
  }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val i = s.indexOf('^')
    val sum = s.zipWithIndex.map{ case (c, j) =>
      c match {
        case '=' | '^' => 0
        case '1' => 1L * (i - j).toLong
        case '2' => 2L * (i - j).toLong
        case '3' => 3L * (i - j).toLong
        case '4' => 4L * (i - j).toLong
        case '5' => 5L * (i - j).toLong
        case '6' => 6L * (i - j).toLong
        case '7' => 7L * (i - j).toLong
        case '8' => 8L * (i - j).toLong
        case '9' => 9L * (i - j).toLong
      }
    }.sum
    sum match {
      case 0L => println("balance")
      case i: Long if i > 0L => println("left")
      case i: Long if i < 0L => println("right")
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val i = s.indexOf('^')
    val sum = s.zipWithIndex.map{ case (c, j) =>
      c match {
        case '=' | '^' => 0
        case '1' => 1 * (i - j)
        case '2' => 2 * (i - j)
        case '3' => 3 * (i - j)
        case '4' => 4 * (i - j)
        case '5' => 5 * (i - j)
        case '6' => 6 * (i - j)
        case '7' => 7 * (i - j)
        case '8' => 8 * (i - j)
        case '9' => 9 * (i - j)
      }
    }.sum
    sum match {
      case 0 => println("balance")
      case i: Int if i > 0 => println("left")
      case i: Int if i < 0 => println("right")
    }
  }
}


Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $$$m$$$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $$$1$$$ to $$$n$$$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.However, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" — thinks Gawry — "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.In how many ways he can do it? Two ways are called different if the remaining common part is different.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le m \le 10$$$) — the number of suspects and the number of asked neighbors. Each of the next $$$m$$$ lines contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that these integers form a correct permutation (that is, each number from $$$1$$$ to $$$n$$$ appears exactly once).

Output a single integer denoting the number of ways to delete some prefix and some suffix of each permutation (possibly empty), such that the remaining parts will be equal and non-empty.

NoteIn the first example, all possible common parts are $$$[1]$$$, $$$[2]$$$, $$$[3]$$$ and $$$[2, 3]$$$.In the second and third examples, you can only leave common parts of length $$$1$$$.

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(0)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case 0 => if (j + 1 < n) input(i)(j + 1) else -1 // uninitialized

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != -1 => -1 // discarding now

          case y => y // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Long): Long = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList, 0, 0))
  }

}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A, R = Array.ofDim[Int](N)
    rep(N) { i =>
      A(i) = ni() - 1
      R(A(i)) = i
    }

    val flag = Array.fill[Boolean](N - 1)(true)
    rep(M - 1) { _ =>
      val B = Array.ofDim[Int](N)
      rep(N) { i => B(i) = ni() - 1 }

      rep(N - 1) { i =>
        val ix = R(B(i))
        if (ix < N - 1) flag(ix) &= A(ix + 1) == B(i + 1)
      }
      val ix = R(B(N - 1))
      if (ix != N - 1) {
        flag(ix) = false
      }
    }

    var ans: Long = N
    var cnt = 0
    rep(flag.length) { i =>
      if (flag(i)) {
        cnt += 1
      } else {
        cnt = 0
      }
      ans += cnt
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val arr = Array.fill(m, n)(in.nextInt - 1)
    val pos = Array.fill(m, n)(0)
    (0 until m).foreach { i =>
      (0 until n).foreach { j =>
        pos(i)(arr(i)(j)) = j
      }
    }
    var ans: Long = 0
    var i = 0

    @inline def ok(x: Int, y: Int): Boolean = (1 until m).forall(i => pos(i)(x) + 1 == pos(i)(y))

    while (i < n) {
      val c = i
      while (i < n - 1 && ok(arr(0)(i), arr(0)(i + 1))) {
        i += 1
      }
      i += 1
      ans += (i - c).toLong * (i - c + 1) / 2
    }

    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(-2)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case -2 => if (j + 1 < n) input(i)(j + 1) else 0                          // uninitialized

          case -1 => -1                                                             // already discarded

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now

          case y => y                                                               // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList, 0, 0))
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(0)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case 0 => if (j + 1 < n) input(i)(j + 1) else -1 // uninitialized

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != -1 => -1 // discarding now

          case y => y // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList, 0, 0))
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(-2)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case -2 => if (j + 1 < n) input(i)(j + 1) else 0 // uninitialized

          case -1 => -1 // already discarded

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now

          case y => y // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + (if (n > 1) computeResult(input(0).toList, 0, 0) else 0))
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(-2)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case -2 => if (j + 1 < n) input(i)(j + 1) else 0                          // uninitialized

          case -1 => -1                                                             // already discarded

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now

          case y => y                                                               // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList.tail, 0, 0))
  }

}


A positive integer $$$x$$$ is called a power of two if it can be represented as $$$x = 2^y$$$, where $$$y$$$ is a non-negative integer. So, the powers of two are $$$1, 2, 4, 8, 16, \dots$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Your task is to represent $$$n$$$ as the sum of exactly $$$k$$$ powers of two.

The only line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le k \le 2 \cdot 10^5$$$).

If it is impossible to represent $$$n$$$ as the sum of $$$k$$$ powers of two, print NO. Otherwise, print YES, and then print $$$k$$$ positive integers $$$b_1, b_2, \dots, b_k$$$ such that each of $$$b_i$$$ is a power of two, and $$$\sum \limits_{i = 1}^{k} b_i = n$$$. If there are multiple answers, you may print any of them.

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = Integer.toBinaryString(N).map(_ - '0').toArray
    val n = A.length
    val cnt = Integer.bitCount(N)
    var k = K - cnt
    var d = 0
    while(k > 0 && d < n - 1) {
      if (A(d) > 0) {
        A(d) -= 1
        A(d + 1) += 2
        k -= 1
      } else {
        d += 1
      }
    }

//    debug(A.mkString)

    if (k == 0) {
      out.println("YES")
      val ans = ArrayBuffer[Int]()
      REP(n) { d =>
        val num = 1 << (n - 1 - d)
        REP(A(d)) { _ =>
          ans += num
        }
      }
      out.println(ans.reverse.mkString(" "))
    } else {
      out.println("NO")
    }
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

object GolfedVersion extends App {
    val sc = new java.util.Scanner(System.in)
    val n0, k0 = sc.nextInt

    def loop(i: Int, n: Int, k: Int): Option[Map[Int, Int]] =
      if (k > n || k < 1) None
      else if (n/2 >= k)  loop(i*2, n/2, k - n%2).map(_ + (i -> n%2))
      else                Some(Map(i*2 -> (n-k), i -> (n - (n-k)*2)))

    print(loop(1, n0, k0).fold("NO")(m =>
      "YES\n" + (for {
        (k, v) <- m.toSeq.sorted
         e     <- Seq.fill(v)(k)
      } yield e).mkString(" ")
    ))
}

object CF_529_3_C {

  type In = (Int, Int)
  type Out = String

  def solve(in: In): Out = {
    val (n0, k0) = in

    def loop(i: Int, bs: Vector[Int], e: Int): Option[Vector[Int]] = (i, e, bs(i)) match {
        // Reached 0, no more to split
      case (0, 0, _)          => Some(bs)
        // Reached 0, nonzero splits required
      case (0, _, _)          => None
        // No splits required, move to next index
      case (_, _, _) if e < 1 => loop(i-1, bs, e)
        // No digits left to split, move to next index
      case (_, _, 0)          => loop(i-1, bs, e)
        // Split a digit
      case (_, _, b)          => loop(i, bs.updated(i-1, bs(i-1) + 2).updated(i, b-1), e - 1)
    }

    val bs = BigInt(n0).toString(2).toVector.map(_.asDigit).reverse

    loop(bs.length - 1, bs, k0 - bs.sum) match {
      case None => "NO"
      case Some (xs) =>
        val seq = for {
            (x, i) <- xs.zipWithIndex
            if x > 0
            e <- Seq.fill(x)(math.pow(2, i).toInt)
          } yield e
        "YES\n" + seq.mkString (" ")
    }
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int)
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_529_3_C {

  type In = (Int, Int)
  type Out = String

  def solve(in: In): Out = {
    val (n0, k0) = in

    def loop(i: Int, n: Int, k: Int): Option[Map[Int, Int]] =
      if (k > n || k < 1) None
      else if (n/2 >= k)
        // join as many as possible
        loop(i * 2, n/2, k - n%2).map(_ + (i -> n%2))
      else {
        // only join as many as required. c = number to join
       val c = n - k
        Some(Map(i * 2 -> c, i -> (n - c*2)))
      }

    loop(1, n0, k0) match {
      case None => "NO"
      case Some(m) =>
        val seq = for {
          (k, v) <- m.toSeq.sorted
           e     <- Seq.fill(v)(k)
        } yield e
        "YES\n" + seq.mkString(" ")
    }
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int)
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!Each grid (main and reserve) has a head node (its number is $$$1$$$). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly $$$n$$$ nodes, which do not spread electricity further.In other words, every grid is a rooted directed tree on $$$n$$$ leaves with a root in the node, which number is $$$1$$$. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.Also, the palace has $$$n$$$ electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device.    In this example the main grid contains $$$6$$$ nodes (the top tree) and the reserve grid contains $$$4$$$ nodes (the lower tree). There are $$$3$$$ devices with numbers colored in blue. It is guaranteed that the whole grid (two grids and $$$n$$$ devices) can be shown in this way (like in the picture above):  main grid is a top tree, whose wires are directed 'from the top to the down',  reserve grid is a lower tree, whose wires are directed 'from the down to the top',  devices — horizontal row between two grids, which are numbered from $$$1$$$ to $$$n$$$ from the left to the right,  wires between nodes do not intersect. Formally, for each tree exists a depth-first search from the node with number $$$1$$$, that visits leaves in order of connection to devices $$$1, 2, \dots, n$$$ (firstly, the node, that is connected to the device $$$1$$$, then the node, that is connected to the device $$$2$$$, etc.).Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of devices in the palace. The next line contains an integer $$$a$$$ ($$$1 + n \le a \le 1000 + n$$$) — the amount of nodes in the main grid. Next line contains $$$a - 1$$$ integers $$$p_i$$$ ($$$1 \le p_i \le a$$$). Each integer $$$p_i$$$ means that the main grid contains a wire from $$$p_i$$$-th node to $$$(i + 1)$$$-th. The next line contains $$$n$$$ integers $$$x_i$$$ ($$$1 \le x_i \le a$$$) — the number of a node in the main grid that is connected to the $$$i$$$-th device. The next line contains an integer $$$b$$$ ($$$1 + n \le b \le 1000 + n$$$) — the amount of nodes in the reserve grid. Next line contains $$$b - 1$$$ integers $$$q_i$$$ ($$$1 \le q_i \le b$$$). Each integer $$$q_i$$$ means that the reserve grid contains a wire from $$$q_i$$$-th node to $$$(i + 1)$$$-th. The next line contains $$$n$$$ integers $$$y_i$$$ ($$$1 \le y_i \le b$$$) — the number of a node in the reserve grid that is connected to the $$$i$$$-th device. It is guaranteed that each grid is a tree, which has exactly $$$n$$$ leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node $$$1$$$, that visits leaves in order of connection to devices.

Print a single integer — the maximal amount of wires that can be cut so that each device is powered.

NoteFor the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red):  The second and the third examples can be seen below:

import scala.collection.mutable

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

  val n, a = nextInt
  val ps = 0 +: nextInts(a - 1).map(_ - 1)
  val xs = nextInts(n).map(_ - 1)
  val b = nextInt
  val qs = 0 +: nextInts(b - 1).map(_ - 1)
  val ys = nextInts(n).map(_ - 1)

  val pChildrenBuilders = Array.fill(a)(new mutable.ArrayBuilder.ofInt)
  for (i <- 1 until ps.length) {
    pChildrenBuilders(ps(i)) += i
  }
  val pChildren = pChildrenBuilders.map(_.result())

  val qChildrenBuilders = Array.fill(b)(new mutable.ArrayBuilder.ofInt)
  for (i <- 1 until qs.length) {
    qChildrenBuilders(qs(i)) += i
  }
  val qChildren = qChildrenBuilders.map(_.result())

  val pl = Array.fill(a)(n)
  val pr, pSize = Array.fill(a)(0)

  val ql = Array.fill(b)(n)
  val qr, qSize = Array.fill(b)(0)

  for (i <- xs.indices) {
    pl(xs(i)) = i
    pr(xs(i)) = i
  }

  for (i <- ys.indices) {
    ql(ys(i)) = i
    qr(ys(i)) = i
  }

  def dfs1p(u: Int): Int = {
    for (v <- pChildren(u)) {
      pSize(u) += dfs1p(v)
      if (pl(v) < pl(u)) pl(u) = pl(v)
      if (pr(v) > pr(u)) pr(u) = pr(v)
    }
    pSize(u) + 1
  }

  def dfs1q(u: Int): Int = {
    for (v <- qChildren(u)) {
      qSize(u) += dfs1q(v)
      if (ql(v) < ql(u)) ql(u) = ql(v)
      if (qr(v) > qr(u)) qr(u) = qr(v)
    }
    qSize(u) + 1
  }

  dfs1p(0)
  dfs1q(0)

  val dp = Array.fill(n)(0)

  for (r <- 0 until n) {
    var p = xs(r)
    var depth = 0
    while (pr(p) == r && p != 0) {
      depth += 1
      val score = pSize(p) + (if (pl(p) == 0) 0 else dp(pl(p) - 1)) + 1
      dp(r) = Math.max(dp(r), score)
      p = ps(p)
    }

    var q = ys(r)
    depth = 0
    while (qr(q) == r && q != 0) {
      depth += 1
      val score = qSize(q) + (if (ql(q) == 0) 0 else dp(ql(q) - 1)) + 1
      dp(r) = Math.max(dp(r), score)
      q = qs(q)
    }
  }

  out.println(dp.last)
  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
  }
}

import scala.collection.mutable

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

  val n, a = nextInt
  val ps = 0 +: nextInts(a - 1).map(_ - 1)
  val xs = nextInts(n).map(_ - 1)
  val b = nextInt
  val qs = 0 +: nextInts(b - 1).map(_ - 1)
  val ys = nextInts(n).map(_ - 1)

  val pChildrenBuilders = Array.fill(a)(new mutable.ArrayBuilder.ofInt)
  for (i <- 1 until ps.length) {
    pChildrenBuilders(ps(i)) += i
  }
  val pChildren = pChildrenBuilders.map(_.result())

  val qChildrenBuilders = Array.fill(b)(new mutable.ArrayBuilder.ofInt)
  for (i <- 1 until qs.length) {
    qChildrenBuilders(qs(i)) += i
  }
  val qChildren = qChildrenBuilders.map(_.result())

  val pl = Array.fill(a)(n)
  val pr = Array.fill(a)(0)

  val ql = Array.fill(b)(n)
  val qr = Array.fill(b)(0)

  for (i <- xs.indices) {
    pl(xs(i)) = i
    pr(xs(i)) = i
  }

  for (i <- ys.indices) {
    ql(ys(i)) = i
    qr(ys(i)) = i
  }

  def dfs1p(u: Int): Unit = {
    for (v <- pChildren(u)) {
      dfs1p(v)
      if (pl(v) < pl(u)) pl(u) = pl(v)
      if (pr(v) > pr(u)) pr(u) = pr(v)
    }
  }

  def dfs1q(u: Int): Unit = {
    for (v <- qChildren(u)) {
      dfs1q(v)
      if (ql(v) < ql(u)) ql(u) = ql(v)
      if (qr(v) > qr(u)) qr(u) = qr(v)
    }
  }

  dfs1p(0)
  dfs1q(0)

  val dpp, dpq = Array.fill(n, n + 1)(0)

  for (r <- 0 until n) {
    for (l <- 0 to r) {
      val dq = if (l > 0) dpq(l - 1).max else 0
      val dp = if (l > 0) dpp(l - 1).max else 0
      var p = xs(r)
      var depth = 0
      while (pr(p) == r && pl(p) >= l && p != 0) {
        depth += 1
        println("---")
        val score = depth + (if (r == 0) 0 else dpp(r - 1)(l)) + dq
        dpp(r)(l) = Math.max(dpp(r)(l), score)
//        if (score > bestP) bestP = score
        p = ps(p)
      }

      var q = ys(r)
      depth = 0
      while (qr(q) == r && ql(q) >= l && q != 0) {
        depth += 1
        val score = depth + (if (r == 0) 0 else dpq(r - 1)(l)) + dp
        dpq(r)(l) = Math.max(dpq(r)(l), score)
        //        if (score > bestP) bestP = score
        q = qs(q)
      }
    }
  }

  out.println(dpq.last.max max dpp.last.max)
  out.flush()

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


You are given a special jigsaw puzzle consisting of $$$n\cdot m$$$ identical pieces. Every piece has three tabs and one blank, as pictured below.  The jigsaw puzzle is considered solved if the following conditions hold:  The pieces are arranged into a grid with $$$n$$$ rows and $$$m$$$ columns.  For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece. Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.

The test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$).

For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).

NoteFor the first test case, this is an example solution:   For the second test case, we can show that no solution exists.For the third test case, this is an example solution:

import scala.io.StdIn.readLine

object A {
  def solution(n: Int, m: Int): Boolean =
    n == 1 || m == 1 || (n == 2 && m == 2)

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(n, m) = readLine.split(" ").toSeq.map(_.toInt)
      println(if (solution(n, m)) "YES" else "NO")
    }
  }
}

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

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    if (n == 1 || m == 1 || n == m && n == 2) println("YES")
    else println("NO")
  }
}

import scala.io.StdIn._

object PuzzlePieces {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    loopWithIndex(n) { i =>
      val l = readLine.split(" ").map(_.toInt).toList
      val c = l(0)
      val r = l(1)
      if (c == 1 || r == 1) println("YES")
      else
        if (c > 2 || r > 2) println("NO")
        else println("YES")
    }
  }

  def loopWithIndex[T](n: Int)(block: Int => T) =
    (1 to n).foreach(e => block(e))
}

object ProblemA extends App {
  import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()

  for (i <- 1 to n) {
    val m = in.nextInt()
    val n = in.nextInt()

    if ((n == 1 || m == 1) || (n == 2 && m == 2)) {
      println("YES")
    } else {
      println("NO")
    }
  }

}

import scala.io.StdIn._

object PuzzlePieces {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    loopWithIndex(n) { i =>
      val l = readLine.split(" ").map(_.toInt).toList
      val c = l(0)
      val r = l(1)
      if ((c == 1 && r == 3) || (c == 3 && r == 1)) println("YES")
      else
        if (c > 2 || r > 2) println("NO")
        else println("YES")
    }
  }

  def loopWithIndex[T](n: Int)(block: Int => T) =
    (1 to n).foreach(e => block(e))
}


Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.

The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.

If the given sequence has the second order statistics, output this order statistics, otherwise output NO.

object Flask {
  def main(args: Array[String]): Unit = {
    readLine
    var data = readLine.split(" ").map(_.toInt)
    if (data.size < 2) { println("NO"); return; }

    var first: Option[Int] = None
    var second: Option[Int] = None
    data.foreach(x => x match {
      case x if first == None || x < first.get => { second = first; first = Some(x) }
      case x if first.get != x && (second == None || x < second.get) => { second = Some(x) }
      case _ => {}
    })
    println( if (second == None) "NO" else second.get)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (f, s) = in.next().split(' ').map(_.toInt).foldLeft(101, 101) {
    case ((min, second), el) if el < min =>
      (el, min)
    case ((min, second), el) if el < second && el != min =>
      (min, el)
    case (acc, el) => acc
  }
  if (s == 101)
    println("NO")
  else
    println(s)
}

object A22 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n).distinct.sorted
    if(input.length == 1) {
      out.println("NO")
    } else {
      out.println(input(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 scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var arr = readLine.split(" ").toList.map(_.toInt);
    var min = arr.min;
    var arrf = arr.filter(p => p != min);
    var result = "NO"
    if (!arrf.isEmpty)
      result = arrf.min.toString;
    println(result);
  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt).toSet.toSeq
    a.sorted.drop(1).headOption match {
      case None => println("NO")
      case Some(i) => println(i)
    }
  }
}

object Flask {
  def main(args: Array[String]): Unit = {
    readLine
    var data = readLine.split(" ").map(_.toInt)
    if (data.size < 3) { println("NO"); return; }

    var first: Option[Int] = None
    var second: Option[Int] = None
    data.foreach(x => x match {
      case x if first == None || x < first.get => { second = first; first = Some(x) }
      case x if first.get != x && (second == None || x < second.get) => { second = Some(x) }
      case _ => {}
    })
    println(second.get)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (f, s) = in.next().split(' ').map(_.toInt).foldLeft(-101, -101) {
    case ((max, second), el) if el > max =>
      (el, max)
    case ((max, second), el) if el > second && el != max =>
      (max, el)
    case (acc, el) => acc
  }
  if (s == -101)
    println("NO")
  else
    println(s)

}