Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.

The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.

Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val max = data.max
  if (max == 1)
    data(data.length - 1) = 2
  else {
    val index = data.indexOf(max)
    data(index) = 1
  }
  println(data.sorted.mkString(" "))
}

object Main {

    def main(args: Array[String]) {
        val n = nextInt()
        val a = (for (i <- 0 until n) yield nextInt()).toList.sorted
        val s = if (a.last == 1) ((a.init):::List(2)) else 1 :: a.init
        println(s.mkString(" "))
    }

    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
    var st = new java.util.StringTokenizer("");

    def next() = {
        while (!st.hasMoreTokens())
            st = new java.util.StringTokenizer(in.readLine());
        st.nextToken();
    }

    def nextInt() = java.lang.Integer.parseInt(next());
    def nextDouble() = java.lang.Double.parseDouble(next());
    def nextLong() = java.lang.Long.parseLong(next());
}

/**
 * @author pvasilyev
 * @since 29 Jun 2016
 */
object A135 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    if (n == 1) {
      if (a(0) == 1) {
        println("2")
      } else {
        println("1")
      }
    } else {
      val buf = new StringBuilder
      if (a(0) != 1) {
        for (i <- 0 until n) {
          if (i == 0) {
            buf ++= "1 "
          } else {
            buf ++= (a(i - 1) + " ")
          }
        }
      } else {
        for (i <- 0 until n) {
          if (i == 0) {
            buf ++= "1 "
          } else if (a(i) == 1) {
            if (i < n - 1 && a(i + 1) == 1) {
              buf ++= "1 "
            } else if (i < n - 1 && a(i + 1) != 1) {
              buf ++= "1 "
            } else {
              buf ++= "2 "
            }
          } else {
            buf ++= (a(i - 1) + " ")
          }
        }
      }
      println(buf.toString())
    }

  }

  solve()

}

import java.util.Scanner

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

  val N = sc.nextInt
  val arr = for (i <- 0 until N) yield sc.nextInt
  if (arr.forall(1 ==)) {
    print(List.make(arr.size - 1, 1).mkString(" "))
    if(arr.size != 1) print(" ")
    println(2)
  } else {
    val vmax = arr.max
    val after = arr.updated(arr.indexOf(vmax), 1).sorted
    println(after.mkString(" "))
  }
}

import scala.util.Sorting
object Main {
  def printArr(a: Array[Int], end: Int) {
    for (i <- 0 to end) {
      if (i != 0)
        print(" ")
      print(a(i))
    }
  }
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(' ').map(_.toInt)
    Sorting.quickSort(a)
    if (a.last == 1) {
      a(a.length-1) = 2
      printArr(a, a.length - 1)
    }
    else {
      print("1 ")
      printArr(a, a.length - 2)
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val max = data.max
  val index = data.indexOf(max)
  data(index) = 1
  println(data.sorted.mkString(" "))
}

import java.util.Scanner

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

  val N = sc.nextInt
  val arr = for(i <- 0 until N) yield sc.nextInt

  val vmax = arr.max
  val after = arr.updated(arr.indexOf(vmax), 1).sorted
  println(after.mkString(" "))
}


You are given an equation:  Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order.

The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0.

In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.

object P020B extends App {
  def solve(a: List[Long]): Tuple3[Int, Any, Any] = {
    val det = a(1)*a(1) - 4*a(0)*a(2)
    if (det < 0) return new Tuple3(0, Unit, Unit);
    val x1 = -0.5*a(1)/a(0)
    if (det == 0) return new Tuple3(1, x1, Unit);
    val x2 = 0.5*math.sqrt(det)/a(0)
    return new Tuple3(2, x1-x2, x1+x2)
  }

  var a = readLine.split(' ').map(_.toLong).toList
  if (a(0) < 0) a = a.map(-_)
  val result = a match {
    case List(0, 0, 0) => (-1, Unit, Unit)
    case 0::0::tail => (0, Unit, Unit)
    case 0::tail => (1, -1.0*a(2)/a(1), Unit)
    case _ => solve(a)
  }
  println(result._1)
  if (result._1 >= 1) printf("%.8f\n", result._2);
  if (result._1 >= 2) printf("%.8f\n", result._3);
}

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

object B {

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

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

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

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

  def solve: Int = {
    val a = nextLong
    val b = nextLong
    val c = nextLong
    if (a == 0 && b == 0 && c == 0) {
      out.println(-1)
      return 1
    }
    if (a == 0 && b == 0) {
      out.println(0)
      return 1
    }
    if (a == 0) {
      out.println(1)
      out.println((1.0d * (-c)) / b)
      return 1
    }
    val d = b * b - 4L * a * c
    if (d < 0) {
      out.println(0)
      return 1
    }
    if (d == 0) {
      out.println(1)
      out.println((1.0d * (-b)) / (2.0d * a))
      return 1
    }
    out.println(2)
    out.println(Math.min( ((1.0d * (-b)) - Math.sqrt(d) )/ (2.0d * a), ((1.0d * (-b)) + Math.sqrt(d) )/ (2.0d * a)))
    out.println(Math.max( ((1.0d * (-b)) - Math.sqrt(d) )/ (2.0d * a), ((1.0d * (-b)) + Math.sqrt(d) )/ (2.0d * a)))
    return 1
  }

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

object P020B extends App {
  def solve(a: List[Int]): Tuple3[Int, Any, Any] = {
    val det = a(1)*a(1) - 4*a(0)*a(2)
    if (det < 0) return new Tuple3(0, Unit, Unit);
    val x1 = -0.5*a(1)/a(0)
    if (det == 0) return new Tuple3(1, x1, Unit);
    val x2 = 0.5*math.sqrt(det)/a(0)
    return new Tuple3(2, x1-x2, x1+x2)
  }

  val a = readLine.split(' ').map(_.toInt).toList
  val result = a match {
    case List(0, 0, 0) => (-1, Unit, Unit)
    case 0::0::tail => (0, Unit, Unit)
    case 0::tail => (1, -1.0*a(2)/a(1), Unit)
    case _ => solve(a)
  }
  println(result._1)
  if (result._1 >= 1) printf("%.8f\n", result._2);
  if (result._1 >= 2) printf("%.8f\n", result._3);
}

object P020B extends App {
  def solve(a: List[Long]): Tuple3[Int, Any, Any] = {
    val det = a(1)*a(1) - 4*a(0)*a(2)
    if (det < 0) return new Tuple3(0, Unit, Unit);
    val x1 = -0.5*a(1)/a(0)
    if (det == 0) return new Tuple3(1, x1, Unit);
    val x2 = 0.5*math.sqrt(det)/a(0)
    return new Tuple3(2, x1-x2, x1+x2)
  }

  val a = readLine.split(' ').map(_.toLong).toList
  val result = a match {
    case List(0, 0, 0) => (-1, Unit, Unit)
    case 0::0::tail => (0, Unit, Unit)
    case 0::tail => (1, -1.0*a(2)/a(1), Unit)
    case _ => solve(a)
  }
  println(result._1)
  if (result._1 >= 1) printf("%.8f\n", result._2);
  if (result._1 >= 2) printf("%.8f\n", result._3);
}

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

object B {

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

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

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

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

  def solve: Int = {
    val a = nextLong
    val b = nextLong
    val c = nextLong
    if (a == 0 && b == 0 && c == 0) {
      out.println(-1)
      return 1
    }
    if (a == 0 && b == 0) {
      out.println(0)
      return 1
    }
    if (a == 0) {
      out.println(1)
      out.println((1.0d * (-c)) / b)
      return 1
    }
    val d = b * b - 4L * a * c
    if (d < 0) {
      out.println(0)
      return 1
    }
    if (d == 0) {
      out.println(1)
      out.println((1.0d * (-b)) / (2.0d * a))
      return 1
    }
    out.println(2)
    out.println(((1.0d * (-b)) - Math.sqrt(d) )/ (2.0d * a))
    out.println(((1.0d * (-b)) + Math.sqrt(d) )/ (2.0d * a))
    return 1
  }

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


There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?Note that outcome of a match can not be a draw, it has to be either win or loss.

The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 105). Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — data for the current test case.

For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).

NoteSample 1. There has not been any match up to now (k = 0, d1 = 0, d2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.Sample 2. You missed all the games (k = 3). As d1 = 0 and d2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".Sample 3. You missed 4 matches, and d1 = 1, d2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).

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

/**
 * Created by arseny on 24.07.14.
 */
object C extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val t = nextInt
    for (i <- 0 until t) {
      val n = nextLong
      val k = nextLong
      val d1 = nextLong
      val d2 = nextLong

      def getPossiblePoints(): List[(Long, Long, Long)] = {
        val x1 = k - d2 - 2 * d1
        val x2 = k + d2 - 2 * d1
        val x3 = k - d2 + 2 * d1
        val x4 = k + d2 + 2 * d1
        var ans = List((-1.toLong, -1.toLong, -1.toLong))
        if (x1 >= 0 && x1 % 3 == 0) {
          val y1 = x1 / 3
          ans = (y1, y1 + d1, y1 + d1 + d2) :: ans
        }
        if (x2 >= 0 && x2 % 3 == 0) {
          val y2 = x2 / 3
          if (y2 + d1 - d2 >= 0) {
            ans = (y2, y2 + d1, y2 + d1 - d2) :: ans
          }
        }
        if (x3 >= 0 && x3 % 3 == 0) {
          val y3 = x3 / 3
          if (y3 - d1 >= 0) {
            ans = (y3, y3 - d1, y3 - d1 + d2) :: ans
          }
        }
        if (x4 >= 0 && x4 % 3 == 0) {
          val y4 = x4 / 3
          if (y4 - d1 - d2 >= 0) {
            ans = (y4, y4 - d1, y4 - d1 - d2) :: ans
          }
        }
        ans.init
      }
      val can = getPossiblePoints()
      val left = n - k
      var g = true
      //out.println(can)
      for (c <- can if g) {
        if ((left + c._1 + c._2 + c._3) % 3 == 0) {
          val z = (left + c._1 + c._2 + c._3) / 3
          if (z >= c._1 && z >= c._2 && z >= c._3 && z >= 0) {
            g = false
          }
        }
      }
      if (!g) {
        out.println("yes")
      } else {
        out.println("no")
      }
    }
  }

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

object Solution extends App {

  def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {
    val shouldWin = n / 3
    val unknown = (k - d1 + d2) % 3
    if (unknown != 0 || first < 0 || second < 0 || third < 0 || first > k
      || second > k || third > k || n % 3 != 0
      || first > shouldWin || second > shouldWin || third > shouldWin)
      return false
    return true
  }

//  for (int sign1 = -1; sign1 <= 1; sign1++) {
//    for (int sign2 = -1; sign2 <= 1; sign2++) {
//      if (sign1 == 0 || sign2 == 0) {
//        continue;
//      }
//      LL D1 = d1 * sign1;
//      LL D2 = d2 * sign2;
//
//      LL x2 = (k - D1 + D2) / 3;
//      if ((k - D1 + D2) % 3 != 0) {
//        continue;
//      }
//      if (x2 >= 0 && x2 <= k) {
//        LL x1 = D1 + x2;
//        LL x3 = x2 - D2;
//        if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {
//          if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {
//            assert(abs(x1 - x2) == d1);
//            assert(abs(x2 - x3) == d2);
//            return true;
//          }
//        }
//      }
//    }
//  }

  def solve(n: Long, k: Long, d1: Long, d2: Long): Boolean = {
    if (n % 3 != 0)
      return false

    (-1 to 1).foreach { sign1 =>
      if (sign1 != 0)
        (-1 to 1).foreach { sign2 =>
          if (sign2 != 0) {
            val D1 = d1 * sign1
            val D2 = d2 * sign2

            val x2 = (k - D1 + D2) / 3
            if ((k - D1 + D2) % 3 == 0 && x2 >= 0 && x2 <= k) {
              val x1 = D1 + x2
              val x3 = x2 - D2
              if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {
                if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {
                  if (Math.abs(x1 - x2) == d1 && Math.abs(x2 - x3) == d2)
                    return true
                }
              }
            }
          }
      }
    }

    false
  }

  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  val res = (1 to t).map { _ =>
    val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)
    if (solve(n, k, d1, d2)) "yes" else "no"
  }
  println(res.mkString("\n"))
}

object Solution extends App {

  def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {
    val shouldWin = n / 3
    val unknown = (k - d1 + d2) % 3
    if (unknown != 0 || first < 0 || second < 0 || third < 0 || first > k
      || second > k || third > k || n % 3 != 0
      || first > shouldWin || second > shouldWin || third > shouldWin)
      return false
    return true
  }

//  for (int sign1 = -1; sign1 <= 1; sign1++) {
//    for (int sign2 = -1; sign2 <= 1; sign2++) {
//      if (sign1 == 0 || sign2 == 0) {
//        continue;
//      }
//      LL D1 = d1 * sign1;
//      LL D2 = d2 * sign2;
//
//      LL x2 = (k - D1 + D2) / 3;
//      if ((k - D1 + D2) % 3 != 0) {
//        continue;
//      }
//      if (x2 >= 0 && x2 <= k) {
//        LL x1 = D1 + x2;
//        LL x3 = x2 - D2;
//        if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {
//          if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {
//            assert(abs(x1 - x2) == d1);
//            assert(abs(x2 - x3) == d2);
//            return true;
//          }
//        }
//      }
//    }
//  }

  def solve(n: Long, k: Long, d1: Long, d2: Long) = {
    val s = List((d1, 0l, d2), (0l, d1, d1 + d2), (0l, d1, d1 - d2), (d2 - d1, d2, 0l), (d1 + d2, d2, 0l)).find{
      case (f, s, t1) => solution(n, k, d1, d2, f, s, t1)
    }
//    println(s)
    s.nonEmpty
  }

  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  val res = (1 to t).map { _ =>
    val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)
    if (solve(n, k, d1, d2)) "yes" else "no"
  }
  println(res.mkString("\n"))
}

object Solution extends App {

  def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {
    val shouldWin = n / 3
    val unknown = (k - d1 + d2) % 3
    if (unknown != 0 || first < 0 || second < 0 || third < 0 || first > k
      || second > k || third > k || n % 3 != 0
      || first > shouldWin || second > shouldWin || third > shouldWin)
      return false
    return true
  }

//  for (int sign1 = -1; sign1 <= 1; sign1++) {
//    for (int sign2 = -1; sign2 <= 1; sign2++) {
//      if (sign1 == 0 || sign2 == 0) {
//        continue;
//      }
//      LL D1 = d1 * sign1;
//      LL D2 = d2 * sign2;
//
//      LL x2 = (k - D1 + D2) / 3;
//      if ((k - D1 + D2) % 3 != 0) {
//        continue;
//      }
//      if (x2 >= 0 && x2 <= k) {
//        LL x1 = D1 + x2;
//        LL x3 = x2 - D2;
//        if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {
//          if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {
//            assert(abs(x1 - x2) == d1);
//            assert(abs(x2 - x3) == d2);
//            return true;
//          }
//        }
//      }
//    }
//  }

  def solve(n: Long, k: Long, d1: Long, d2: Long): Boolean = {
    if (n % 3 != 0)
      return false

    (-1 to 1).foreach { sign1 =>
      if (sign1 != 0)
        (-1 to 1).foreach { sign2 =>
          if (sign2 == 0) {
            val D1 = d1 * sign1
            val D2 = d2 * sign2

            val x2 = (k - D1 + D2) / 3
            if ((k - D1 + D2) % 3 == 0 && x2 >= 0 && x2 <= k) {
              val x1 = D1 + x2
              val x3 = x2 - D2
              if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {
                if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {
                  if (Math.abs(x1 - x2) == d1 && Math.abs(x2 - x3) == d2)
                    return true
                }
              }
            }
          }
      }
    }

    false
  }

  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  val res = (1 to t).map { _ =>
    val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)
    if (solve(n, k, d1, d2)) "yes" else "no"
  }
  println(res.mkString("\n"))
}

object Solution extends App {

  def solution(n: Long, k: Long, d1: Long, d2: Long, first: Long, second: Long, third: Long): Boolean = {
    val shouldWin = n / 3
    if (first < 0 || second < 0 || third < 0 || first > k
      || second > k || third > k || n % 3 != 0
      || first > shouldWin || second > shouldWin || third > shouldWin)
      return false
    return true
  }

  def solve(n: Long, k: Long, d1: Long, d2: Long) = {
    val s = List((d1, 0l, d2), (0l, d1, d1 + d2), (0l, d1, d1 - d2), (d2 - d1, d2, 0l), (d1 + d2, d2, 0l)).find{
      case (f, s, t1) => solution(n, k, d1, d2, f, s, t1)
    }
//    println(s)
    s.nonEmpty
  }

  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  val res = (1 to t).map { _ =>
    val Array(n, k, d1, d2) = in.next().split(' ').map(_.toLong)
    if (solve(n, k, d1, d2)) "yes" else "no"
  }
  println(res.mkString("\n"))
}


Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).

Print the single number — the maximum number of frames Nicholas can make for his future canvases.

object Flask {

  def main(args: Array[String]): Unit = {
    readLine
    var input = readLine.split(" ").map(_.toInt)
    var index: Map[Int, Int] = Map[Int, Int]()

    for (x <- input) {
      if (index.contains(x))
        index += (x -> (index(x) + 1))
      else
        index += (x -> 1)
    }

    var total = index.keys.foldLeft(0)((res, x) => res + index(x) / 2) / 2
    println(total)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split(' ').map(_.toInt).groupBy(x => x).map(_._2.length / 2).sum / 2)
}

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

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

  val res = List.fill(sc.nextInt)(sc.nextInt).groupBy(identity).values.map(_.size / 2).sum / 2

  out.println(res)
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)
  def readLine = reader.readLine

  readInt
  def ans = readInts.groupBy(x => x).values.map(_.size / 2).sum / 2

  def main(a: Array[String]) {
    println(ans)
  }
}

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


You are given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \cdot a_2$$$ $$$\dots$$$ $$$\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\cdot (-1) \cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the numbers.

Output a single number — the minimal number of coins you need to pay to make the product equal to $$$1$$$.

NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin.

import scala.annotation.tailrec
import scala.collection.immutable
import scala.io.StdIn._
object Main extends App {
  val n = readInt
  val numbers = readLine.trim.split(' ').map(_.toLong)
  val (positive, negative) = numbers.partition(_ >= 0)
  val zero = numbers.filter(_ == 0L)
  val forPos = positive.sum - positive.length + zero.length
  val forNeg = - negative.sum - negative.length
  if (negative.length % 2 == 0 || zero.nonEmpty){
    println(forPos + forNeg + zero.length)
  }else {
    println(forPos + forNeg + 2)
  }
}

import scala.io.StdIn._

object B_1206 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  var value = 0L
  var pos = 0
  var neg = 0

  for (i <- 0 until n) {
    A(i) = if (A(i) > 0) {
      value += A(i) - 1
      pos += 1
      1
    } else if (A(i) < 0) {
      value += -A(i) - 1
      neg += 1
      -1
    } else {
      0
    }
  }

  val zeroes = n - pos - neg
  if (zeroes == 0) {
    if (neg % 2 == 1) value += 2
  } else {
    value += zeroes
  }

  println(value)
}

import scala.io.StdIn._

object B_1206 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  var cost  = 0L
  var value = 0
  var pos = 0
  var neg = 0

  for (i <- 0 until n) {
    A(i) = if (A(i) > 0) {
      value += A(i) - 1
      pos += 1
      1
    } else if (A(i) < 0) {
      value += -A(i) - 1
      neg += 1
      -1
    } else {
      0
    }
  }

  val zeroes = n - pos - neg
  if (zeroes == 0) {
    if (neg % 2 == 1) value += 2
  } else {
    value += zeroes
  }

  println(value)
}


You are organizing a boxing tournament, where $$$n$$$ boxers will participate ($$$n$$$ is a power of $$$2$$$), and your friend is one of them. All boxers have different strength from $$$1$$$ to $$$n$$$, and boxer $$$i$$$ wins in the match against boxer $$$j$$$ if and only if $$$i$$$ is stronger than $$$j$$$.The tournament will be organized as follows: $$$n$$$ boxers will be divided into pairs; the loser in each pair leaves the tournament, and $$$\frac{n}{2}$$$ winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.Furthermore, during each stage you distribute the boxers into pairs as you wish.The boxer with strength $$$i$$$ can be bribed if you pay him $$$a_i$$$ dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2^{18}$$$) — the number of boxers. $$$n$$$ is a power of $$$2$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ is the number of dollars you have to pay if you want to bribe the boxer with strength $$$i$$$. Exactly one of $$$a_i$$$ is equal to $$$-1$$$ — it means that the boxer with strength $$$i$$$ is your friend. All other values are in the range $$$[1, 10^9]$$$.

Print one integer — the minimum number of dollars you have to pay so your friend wins.

NoteIn the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.In the second test case you can distribute boxers as follows (your friend is number $$$2$$$):$$$1 : 2, 8 : 5, 7 : 3, 6 : 4$$$ (boxers $$$2, 8, 7$$$ and $$$6$$$ advance to the next stage);$$$2 : 6, 8 : 7$$$ (boxers $$$2$$$ and $$$8$$$ advance to the next stage, you have to bribe the boxer with strength $$$6$$$);$$$2 : 8$$$ (you have to bribe the boxer with strength $$$8$$$);

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._

  /**
    * log2して小数点切り捨てたもの
    */
  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N - 1)
    val ix = A.indexWhere(_ == -1)
    TO(ix, N - 2) { i =>
      B(i) = A(i + 1)
    }

    var k = log2(N) - 1
    val minimum = new java.util.PriorityQueue[Int]
    var ans = B(N - 2).toLong
    var i = N - 3
    while(k > 0) {
      REP(1 << k) { _ =>
        minimum.add(B(i))
        i -= 1
      }
      ans += minimum.poll()
      k -= 1
    }

    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._

  /**
    * log2して小数点切り捨てたもの
    */
  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  case class Entry(a: Int, i: Int)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    import java.util
    import java.util.Comparator
    val N = ni()
    val A = na(N)
    val ix = A.indexWhere(_ == -1)

    var ans = 0L
    val q = new util.TreeSet[Entry](new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = {
        if (o1.a == o2.a) {
          Integer.compare(o2.i, o1.i) // 降順
        } else {
          Integer.compare(o2.a, o1.a) // 降順
        }
      }
    })
    val remains = new util.TreeSet[Int](new Comparator[Int] {
      override def compare(o1: Int, o2: Int): Int = Integer.compare(o2, o1) // 降順
    })
    TO(ix + 1, N - 1) { i =>
      q.add(Entry(A(i), i))
      remains.add(i)
    }

    var k = log2(N) - 1
    while(!remains.isEmpty) {
      val i = remains.pollFirst()
      q.remove(Entry(A(i), i))
      debug(s"k:$k A(i):${A(i)}")
      ans += A(i)
      REP(min(q.size(), (1 << k) - 1)) { _ =>
        val entry = q.pollFirst()
        remains.remove(entry.i)
      }
      k -= 1
    }

    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._

  /**
    * log2して小数点切り捨てたもの
    */
  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N - 1)
    val ix = A.indexWhere(_ == -1)
    TO(ix, N - 2) { i =>
      B(i) = A(i + 1)
    }

    var k = log2(N) - 1
    val minimum = new java.util.PriorityQueue[Int]
    var ans = B(N - 2)
    var i = N - 3
    while(k > 0) {
      REP(1 << k) { _ =>
        minimum.add(B(i))
        i -= 1
      }
      ans += minimum.poll()
      k -= 1
    }

    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._

  /**
    * log2して小数点切り捨てたもの
    */
  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  case class Entry(a: Int, i: Int)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    import java.util
    import java.util.Comparator
    val N = ni()
    val A = na(N)
    val ix = A.indexWhere(_ == -1)

    var ans = 0L
    val q = new util.TreeSet[Entry](new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = {
        if (o1.a == o2.a) {
          Integer.compare(o1.i, o2.i)
        } else {
          Integer.compare(o2.a, o1.a) // 降順
        }
      }
    })
    val remains = new util.TreeSet[Int](new Comparator[Int] {
      override def compare(o1: Int, o2: Int): Int = Integer.compare(o2, o1) // 降順
    })
    TO(ix + 1, N - 1) { i =>
      q.add(Entry(A(i), i))
      remains.add(i)
    }

    var k = log2(N) - 1
    while(!remains.isEmpty) {
      val i = remains.pollFirst()
      q.remove(Entry(A(i), i))
      debug(s"k:$k A(i):${A(i)}")
      ans += A(i)
      REP((1 << k) - 1) { _ =>
        val entry = q.pollFirst()
        remains.remove(entry.i)
      }
      k -= 1
    }

    out.println(ans)
  }
}


Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.

The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit. The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis. The next m lines contain information about the lanes. The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.

In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.

NoteIn the first example Oleg visiting banks by path 1 → 6 → 2 → 4.Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.In the second example Oleg can visit banks by path 4 → 1 → 3.

import scala.collection.mutable
// package main

/**
  * Created by velizar on 12/05/17.
  */
object Main extends App {

  import scala.io.Source
  import collection.mutable.Map

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n, k) = input(0)
  val Array(m) = input(1)
  val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }
                               .filter{ case (from, to, _) => from != to }
  val nAug = n + 1
  val maxValue = 1000 * 80 + 20000 // = 100000

  // edges(from) = ArrayBuffer[(to, cost])
  val edges: Array[Vector[(Int, Int)]] = Array.fill(nAug)(Vector.empty)
  inputEdges.foreach { case (from, to, cost) =>
    val existingEdge = edges(from).find { case(dst, _) => dst == to }
    existingEdge match {
      case Some((_, prevCost)) if cost < prevCost =>
        val idx = edges(from).indexOf((to, prevCost))
        edges(from) = edges(from).updated(idx, (to, cost))
      case _ =>
        edges(from) = edges(from) :+ ((to, cost))
    }
  }
  for (i <- 0 until n)
    edges(n) = edges(n) :+ ((i, 0))

  /*
  val boundEdges = for {
    pos <- 0 until nAug
  } yield for {
    bound <- 0 until nAug
  } yield {
    val edgesPosB = for {
      (next, cost) <- edges(pos)
      if next != pos
      if bound != pos
      isLower = bound < pos
      if (isLower && next >= bound && next < pos) || (!isLower && next <= bound && next > pos)
    } yield (next, cost)
    edgesPosB.view.sortBy(_._2)
  }
  */

  val boundUnsortedEdges = for {
    pos <- 0 until nAug
  } yield for {
    bound <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if next != pos
    if bound != pos
    isLower = bound < pos
    if (isLower && next >= bound && next < pos) || (!isLower && next <= bound && next > pos)
  } yield (next, cost)

  /*
  // (cost, bound, pos, k)
  type State2 = (Int, Int, Int, Int)
  def nextEdges2(bound: Int, pos: Int, k: Int,
                costAcc: Int = 0, offset: Int = 0):
  Stream[State2] = {
    val (next, cost) = boundEdges(pos)(bound).lift(offset).getOrElse((0, maxValue))
    if (cost == maxValue)
      Stream.Empty
    else
      (costAcc + cost, bound min pos+1, next, k - 1) #::
      (costAcc + cost, pos-1 max bound, next, k - 1) #::
      nextEdges2(bound, pos, k, costAcc, offset + 1)
  }

  // (cost, lb, ub, pos, k)
  type State = (Int, Int, Int, Int, Int)
  def nextEdges(lb: Int, ub: Int, pos: Int, k: Int,
                costAcc: Int = 0, offsetS: Int = 0, offsetL: Int = 0):
  Stream[State] = {
    val smaller = smallerEdges(pos)(lb).lift(offsetS).getOrElse((0, maxValue))
    val larger = largerEdges(pos)(ub).lift(offsetL).getOrElse((0, maxValue))
    val (next, cost) = Seq(smaller, larger).minBy(_._2)
    if (cost == maxValue)
      Stream.Empty
    else if (cost == smaller._2)
      (costAcc + cost, lb, pos - 1, next, k - 1) #::
        nextEdges(lb, ub, pos, k, costAcc, offsetS + 1, offsetL)
    else
      (costAcc + cost, pos + 1, ub, next, k - 1) #::
        nextEdges(lb, ub, pos, k, costAcc, offsetS, offsetL + 1)
  }

  def solveDijkstra(lb: Int, ub: Int, pos: Int, k: Int): Option[Int] = {
    if (k == 0)
      return Some(0)
    val pq = mutable.PriorityQueue.empty[(State, Stream[State])](Ordering.by(-_._1._1))
    val firstState #:: firstStream = nextEdges(lb, ub, pos, k)
    pq += ((firstState, firstStream))
    var endState: Option[State] = None
    while (endState.isEmpty && pq.nonEmpty) {
      val ((cost, lb, ub, pos, k), currentStream) = pq.dequeue
      if (k == 0)
        endState = Some(cost, lb, ub, pos, k)
      val nextStream = nextEdges(lb, ub, pos, k, costAcc = cost)
      Seq(currentStream, nextStream).foreach {
        case Stream.Empty =>
        case (value #:: stream) => pq += ((value, stream))
      }
    }
    endState match {
      case Some((cost, _, _, _, _)) => Some(cost)
      case None => None
    }
  }
  */

  val memo = Map.empty[(Int, Int, Int), Int]

  def solveInner(bound: Int, pos: Int, k: Int): Int = {
    val minCost = boundUnsortedEdges(pos)(bound).map { case (next, cost) =>
      cost + solve(bound min pos+1, next, k - 1) min
      cost + solve(pos-1 max bound, next, k - 1)
    }.fold(maxValue)(_ min _)
    memo((bound, pos, k)) = minCost
    minCost
  }

  def solve(bound: Int, pos: Int, k: Int): Int = {
    if (k == 0) {
      0
    } else {
      memo.get(bound, pos, k) match {
        case Some(s) => s
        case None => solveInner(bound, pos, k)
      }
    }
  }

  val res = solve(0, n, k)
  if (res == maxValue)
    print(-1)
  else
    print(res)
}

// package main

/**
  * Created by velizar on 12/05/17.
  */
object Main extends App {

  import scala.io.Source
  import collection.mutable.{ArrayBuffer, Map}

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n, k) = input(0)
  val Array(m) = input(1)
  val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }
                               .filter{ case (from, to, _) => from != to }
  val nAug = n + 1
  val maxValue = 1000 * 80 + 10000

  // edges(from) = ArrayBuffer[(to, cost])
  val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)
  inputEdges.foreach { case (from, to, cost) =>
    val existingEdge = edges(from).find { case(dst, _) => dst == to }
    existingEdge match {
      case Some((s: Int, prevCost: Int)) if prevCost < cost =>
        val idx = edges(from).indexOf((to, prevCost))
        edges(from)(idx) = (to, cost)
      case _ =>
        edges(from) += ((to, cost))
    }
  }
  for (i <- 0 until n)
    edges(n) += ((i, 0))

  val smallerEdges = for {
    pos <- 0 until nAug
  } yield for {
    lb <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if lb <= next
    if next < pos
  } yield (next, cost)

  val largerEdges = for {
    pos <- 0 until nAug
  } yield for {
    ub <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if pos < next
    if next <= ub
  } yield (next, cost)

  val memo = Map.empty[(Int, Int, Int, Int), Int]

  def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>
      cost + solve(lb, pos - 1, next, k - 1)
    }
    val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>
      cost + solve(pos + 1, ub, next, k - 1)
    }
    val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min
    memo((lb, ub, pos, k)) = minAns
    minAns
  }

  def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    if (k == 0) {
      0
    } else {
      memo.get(lb, ub, pos, k) match {
        case Some(s) => s
        case None => solveInner(lb, ub, pos, k)
      }
    }
  }

  val res = solve(0, n - 1, n, k)
  val printableRes = if (res >= maxValue) -1 else res
  print(printableRes)
}

// package main

/**
  * Created by velizar on 12/05/17.
  */
object Main extends App {

  import scala.io.Source
  import collection.mutable.{ArrayBuffer, Map}

  val input = Source.fromInputStream(System.in).getLines.toVector.dropRight(2).map(_.split(" ").map(_.toInt))
  val Array(n, k) = input(0)
  val Array(m) = input(1)
  val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }
                                .filter{ case (from, to, _) => from != to }
  val nAug = n + 1
  val maxValue = 1000 * 80 + 10000

  // edges(from) = ArrayBuffer[(to, cost])
  val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)
  inputEdges.foreach { case (from, to, cost) =>
      val existingEdge = edges(from).find { case(dst, _) => dst == to }
      existingEdge match {
        case Some((_, prevCost)) if prevCost < cost =>
          val idx = edges(from).indexOf((to, prevCost))
          edges(from)(idx) = (to, cost)
        case None =>
          edges(from) += ((to, cost))
      }
  }
  for (i <- 0 until n)
    edges(n) += ((i, 0))

  val smallerEdges = for {
    pos <- 0 until nAug
  } yield for {
    lb <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if lb <= next
    if next < pos
  } yield (next, cost)

  val largerEdges = for {
    pos <- 0 until nAug
  } yield for {
    ub <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if pos < next
    if next <= ub
  } yield (next, cost)

  val memo = Map.empty[(Int, Int, Int, Int), Int]

  def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>
      cost + solve(lb, pos - 1, next, k - 1)
    }
    val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>
      cost + solve(pos + 1, ub, next, k - 1)
    }
    val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min
    memo((lb, ub, pos, k)) = minAns
    minAns
  }

  def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    if (k == 0) {
      0
    } else {
      memo.get(lb, ub, pos, k) match {
        case Some(s) => s
        case None => solveInner(lb, ub, pos, k)
      }
    }
  }

  val res = solve(0, n - 1, n, k)
  val printableRes = if (res >= maxValue) -1 else res
  print(printableRes)
}

// package main

/**
  * Created by velizar on 12/05/17.
  */
object Main extends App {

  import scala.io.Source
  import collection.mutable.{ArrayBuffer, Map}

  val input = Source.fromInputStream(System.in).getLines.toVector.init.map(_.split(" ").map(_.toInt))
  val Array(n, k) = input(0)
  val Array(m) = input(1)
  val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }
                                .filter{ case (from, to, _) => from != to }
  val nAug = n + 1
  val maxValue = 1000 * 80 + 10000

  // edges(from) = ArrayBuffer[(to, cost])
  val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)
  inputEdges.foreach { case (from, to, cost) =>
      val existingEdge = edges(from).find { case(dst, _) => dst == to }
      existingEdge match {
        case Some((_, prevCost)) if prevCost < cost =>
          val idx = edges(from).indexOf((to, prevCost))
          edges(from)(idx) = (to, cost)
        case None =>
          edges(from) += ((to, cost))
      }
  }
  for (i <- 0 until n)
    edges(n) += ((i, 0))

  val smallerEdges = for {
    pos <- 0 until nAug
  } yield for {
    lb <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if lb <= next
    if next < pos
  } yield (next, cost)

  val largerEdges = for {
    pos <- 0 until nAug
  } yield for {
    ub <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if pos < next
    if next <= ub
  } yield (next, cost)

  val memo = Map.empty[(Int, Int, Int, Int), Int]

  def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>
      cost + solve(lb, pos - 1, next, k - 1)
    }
    val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>
      cost + solve(pos + 1, ub, next, k - 1)
    }
    val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min
    memo((lb, ub, pos, k)) = minAns
    minAns
  }

  def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    if (k == 0) {
      0
    } else {
      memo.get(lb, ub, pos, k) match {
        case Some(s) => s
        case None => solveInner(lb, ub, pos, k)
      }
    }
  }

  val res = solve(0, n - 1, n, k)
  val printableRes = if (res >= maxValue) -1 else res
  print(printableRes)
}

// package main

/**
  * Created by velizar on 12/05/17.
  */
object Main extends App {

  import scala.io.Source
  import collection.mutable.{ArrayBuffer, Map}

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n, k) = input(0)
  val Array(m) = input(1)
  val inputEdges = input.drop(2).map{ case Array(from, to, cost) => (from - 1, to - 1, cost) }
                               .filter{ case (from, to, _) => from != to }
  val nAug = n + 1
  val maxValue = 1000 * 80 + 10000

  // edges(from) = ArrayBuffer[(to, cost])
  val edges: Array[ArrayBuffer[(Int, Int)]] = Array.fill(nAug)(ArrayBuffer.empty)
  inputEdges.foreach { case (from, to, cost) =>
    val existingEdge = edges(from).find { case(dst, _) => dst == to }
    existingEdge match {
      case Some((_, prevCost)) if cost < prevCost =>
        val idx = edges(from).indexOf((to, prevCost))
        edges(from)(idx) = (to, cost)
      case _ =>
        edges(from) += ((to, cost))
    }
  }
  for (i <- 0 until n)
    edges(n) += ((i, 0))

  val smallerEdges = for {
    pos <- 0 until nAug
  } yield for {
    lb <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if lb <= next
    if next < pos
  } yield (next, cost)

  val largerEdges = for {
    pos <- 0 until nAug
  } yield for {
    ub <- 0 until nAug
  } yield for {
    (next, cost) <- edges(pos)
    if pos < next
    if next <= ub
  } yield (next, cost)

  val memo = Map.empty[(Int, Int, Int, Int), Int]

  def solveInner(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    val costs_1 = smallerEdges(pos)(lb).map { case (next, cost) =>
      cost + solve(lb, pos - 1, next, k - 1)
    }
    val costs_2 = largerEdges(pos)(ub).map { case (next, cost) =>
      cost + solve(pos + 1, ub, next, k - 1)
    }
    val minAns = Seq(costs_1, costs_2, Seq(maxValue)).flatten.min
    memo((lb, ub, pos, k)) = minAns
    println((lb, ub, pos, k, minAns))
    minAns
  }

  def solve(lb: Int, ub: Int, pos: Int, k: Int): Int = {
    if (k == 0) {
      0
    } else {
      memo.get(lb, ub, pos, k) match {
        case Some(s) => s
        case None => solveInner(lb, ub, pos, k)
      }
    }
  }

  val res = solve(0, n - 1, n, k)
  val printableRes = if (res >= maxValue) -1 else res
  print(printableRes)
}


After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $$$n$$$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string $$$s$$$ of length $$$n$$$, where $$$s_i = \texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $$$s_1$$$) and his goal is to get to the last crossroad (which corresponds to $$$s_n$$$).If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \ldots, j-1$$$ there is a bus station, one can pay $$$a$$$ roubles for the bus ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the bus (it is not necessary to have a bus station at the $$$j$$$-th crossroad). Formally, paying $$$a$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \texttt{A}$$$ for all $$$i \le t < j$$$. If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \ldots, j-1$$$ there is a tram station, one can pay $$$b$$$ roubles for the tram ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the tram (it is not necessary to have a tram station at the $$$j$$$-th crossroad). Formally, paying $$$b$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \texttt{B}$$$ for all $$$i \le t < j$$$.For example, if $$$s$$$="AABBBAB", $$$a=4$$$ and $$$b=3$$$ then Petya needs:  buy one bus ticket to get from $$$1$$$ to $$$3$$$,  buy one tram ticket to get from $$$3$$$ to $$$6$$$,  buy one bus ticket to get from $$$6$$$ to $$$7$$$. Thus, in total he needs to spend $$$4+3+4=11$$$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $$$s_n$$$) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the $$$n$$$-th crossroad. After the party he has left with $$$p$$$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad $$$i$$$ to go on foot the first, so he has enough money to get from the $$$i$$$-th crossroad to the $$$n$$$-th, using only tram and bus tickets.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case consists of three integers $$$a, b, p$$$ ($$$1 \le a, b, p \le 10^5$$$) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string $$$s$$$, where $$$s_i = \texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad ($$$2 \le |s| \le 10^5$$$). It is guaranteed, that the sum of the length of strings $$$s$$$ by all test cases in one test doesn't exceed $$$10^5$$$.

For each test case print one number — the minimal index $$$i$$$ of a crossroad Petya should go on foot. The rest of the path (i.e. from $$$i$$$ to $$$n$$$ he should use public transport).

5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    val cost = Array(0,0,0)
    val A = Array.fill(100001)(0)
    val DP = Array.fill(100001)(Array.fill(3)(0L))
    (1 to t).foreach{ _ =>
      val (a,b,p) = (in.nextInt(),in.nextInt(),in.nextInt())
      cost(0) = 0
      cost(1) = a
      cost(2) = b
      val s = in.next()
      s.zipWithIndex.foreach{ case (ch,i) =>
          A(i) = ch match {
            case 'A' => 1
            case 'B' => 2
            case _ => throw new IllegalArgumentException("wtf")
          }
      }

      val n = s.length-1
      DP(n)(0) = 0L
      DP(n)(1) = 0L
      DP(n)(2) = 0L
      for{
        i <- (0 until n).reverse
        prev <- (0 to 2)
      }yield{
        if(A(i) == prev){
          DP(i)(prev) = 0L+DP(i+1)(prev)
        }else{
          DP(i)(prev) = cost(A(i)) + DP(i+1)(A(i))
        }
      }
      //println((0 to n).map(i => DP(i)(0)).mkString(" - "))
      val stationsOk = (0 to n).takeWhile(i => DP(i)(0) > p)
      out.println(stationsOk.length+1)

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.  Current character pointer (CP);  Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence.  If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one.  If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1, s2, ..., sn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language.

The first line of input contains two integers n and q (1 ≤ n, q ≤ 105) — represents the length of the sequence s and the number of queries.  The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces.  The next q lines each contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query.

For each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.

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

object Main extends App {
  val sc = new Scanner(System.in)
  val n, q = sc.nextInt()
  val s = sc.next()

  def simulate(str: String): Seq[Int] = {
    val res = Array.tabulate(10)(_ => 0)
    def run(cp: DoubleLinkedList[Char], dp: Boolean) {
      val c = cp(0)
      val ndp = c match {
        case '>' => true
        case '<' => false
        case _ => dp
      }
      val ncp = if (ndp) cp.next else cp.prev
      if (c >= '0' && c <= '9') {
        res(c - '0') += 1
        if (c != '0') cp(0) = (cp(0) - 1).toChar
        else cp.remove()
      }
      if (ncp == null || ncp.isEmpty) return
      val nc = ncp(0)
      if ((c == '>' || c == '<') && (nc == '>' || nc == '<')) {
        cp.remove()
      }
      run(ncp, ndp)
    }
    run(DoubleLinkedList(str: _*), true)
    return res
  }

  for(_ <- 1 to q) {
    val l, r = sc.nextInt
    println(simulate(s.substring(l - 1, r)).mkString(" "))
  }
}

import scala.collection.mutable.DoubleLinkedList
import java.util._

object CodeForces {

  def SolveSubTask(seq: String) {
    val ans = new Array[Int](10)
    def go(CP: DoubleLinkedList[Char], DP : Boolean  ) {
      val c = CP(0)
      val nDP = c match {
        case '>' => true
        case '<' => false
        case _ => DP
      }
      val nCP = if(nDP) CP.next else CP.prev
      if( c.isDigit ){
        ans(c - '0') += 1
        if(c == '0') CP.remove()
        else CP(0) = (c - 1).toChar
      }
      if(nCP == null || nCP.isEmpty) return
      val nc = nCP(0)
      if( !nc.isDigit && !c.isDigit )
          CP.remove()
      go(nCP,nDP)
    }
    go(DoubleLinkedList(seq: _*) , true)
    System.out.println( ans.mkString(" ") )
  }
  def main(args: Array[String]) {
    val cin = new Scanner(System.in)
    val n = cin.nextInt()
    val q = cin.nextInt()
    val s = cin.next()

    for (i <- 0 until q) {
      val l = cin.nextInt()
      val r = cin.nextInt()
      val seq = s.substring(l - 1, r)
      SolveSubTask(seq)
    }

  }
}

object Olymp{
  def main(args: Array[String]): Unit = {
	val Array(n, q) = readLine.split(' ').map(Integer.parseInt(_))
	val s = readLine.toList
	for (i <- 1 to q) {
	  val Array(l, r) = readLine.split(' ').map(Integer.parseInt(_))
	  solve(Nil, s.drop(l-1).take(r-l+1), '>', Vector.fill(10)(0))
	}
  }

  def solve(prev: List[Char], cur: List[Char], dir: Char, cnt: Vector[Int]): Unit = (prev, cur, dir) match {
    case (_, '0' :: xs, '>') => solve(prev, xs, '>', cnt.updated(0, cnt(0)+1))
    case (y :: ys, '0' :: xs, '<') => solve(ys, y :: xs, '<', cnt.updated(0, cnt(0) + 1))
    case (_, x :: xs, '>') if x.isDigit => solve((x-1).toChar :: prev, xs, '>', cnt.updated(x - '0', cnt(x - '0')+1))
    case (y :: ys, x :: xs, '<') if x.isDigit => solve(ys, y :: (x-1).toChar :: xs, '<', cnt.updated(x - '0', cnt(x - '0') + 1))
    case (_, '>' :: x :: xs, _) if !x.isDigit => solve(prev, x :: xs, '>', cnt)
    case (y :: ys, '<' :: xs, _) if !y.isDigit => solve(ys, y :: xs, '<', cnt)
    case (_, '>' :: xs, _) => solve('>' :: prev, xs, '>', cnt)
    case (y :: ys, '<' :: xs, _) => solve(ys, y :: '<' :: xs, '<', cnt)
    case (_, x :: xs, _) if x.isDigit => for { i <- cnt.updated(x - '0', cnt(x - '0') + 1) } print(i + " "); println
    case _ => for { i <- cnt } print(i + " "); println
  }
}

object CodeForces {

  def SolveSubTask(seq: java.lang.String) {
    val ans = new Array[Int](10)
    def go(CP: Int, DP: Int, subseq: java.lang.String, pos: Int) { // DP 1 right -1 left
      val len = subseq.length()
      if (CP >= 0 && CP < len) {
        pos match {
          case -1 => {
            subseq.charAt(CP) match {
              case '<' => go(CP - 1, -1, subseq, CP)
              case '>' => go(CP + 1, 1, subseq, CP)
              case x => {
                ans(x - '0') += 1
                x match {
                  case '0' => {
                    val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()
                    DP match{
                      case 1 => go(CP, DP, nextseq, -1)
                      case -1 => go(CP + DP, DP, nextseq, -1)
                    }

                  }
                  case y => {
                    val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, nextseq, CP)
                  }
                }
              }
            }
          }
          case others => {
            subseq.charAt(CP) match {
              case '<' => {
                if (!subseq.charAt(pos).isDigit) {
                  val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()
                  go(CP - 1, -1, nextseq, -1)
                } else {
                  go(CP - 1, -1, subseq, CP)
                }
              }
              case '>' => {
                if (!subseq.charAt(pos).isDigit) {
                  val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()
                  go(CP, 1, nextseq, -1)
                } else {
                  go(CP + 1, 1, subseq, CP)
                }
              }
              case x => {
                ans(x - '0') += 1
                x match {
                  case '0' => {
                    val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()
                    DP match{
                      case 1 => go(CP, DP, nextseq, -1)
                      case -1 => go(CP + DP, DP, nextseq, -1)
                    }
                  }

                  case y => {
                    val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, nextseq, CP)
                  }
                }
              }
            }
          }
        }
      } else {
        for (it <- ans) System.out.print(it + " ")
        System.out.println()
      }
    }

    go(0, 1, seq, -1)
  }
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val q = cin.nextInt()
    val s = cin.next()

    for (i <- 0 until q) {
      val l = cin.nextInt()
      val r = cin.nextInt()
      val seq = s.subSequence(l - 1, r).toString()
      SolveSubTask(seq)
    }

  }
}

object CodeForces {

  def SolveSubTask(seq: java.lang.String) {
    val ans = new Array[Int](10)
    def go(CP: Int, DP: Int, subseq: java.lang.String, pos: Int) { // DP 1 right -1 left
      val len = subseq.length()
      if (CP >= 0 && CP < len) {
        pos match {
          case -1 => {
            subseq.charAt(CP) match {
              case '<' => go(CP - 1, -1, subseq, CP)
              case '>' => go(CP + 1, 1, subseq, CP)
              case x => {
                ans(x - '0') += 1
                x match {
                  case '0' => {
                    val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()
                    DP match{
                      case 1 => go(CP, DP, nextseq, -1)
                      case 0 => go(CP + DP, DP, nextseq, -1)
                    }

                  }
                  case y => {
                    val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, subseq, CP)
                  }
                }
              }
            }
          }
          case others => {
            subseq.charAt(CP) match {
              case '<' => {
                if (!subseq.charAt(pos).isDigit) {
                  val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()
                  go(CP - 1, -1, nextseq, -1)
                } else {
                  go(CP - 1, -1, subseq, CP)
                }
              }
              case '>' => {
                if (!subseq.charAt(pos).isDigit) {
                  val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()
                  go(CP, 1, nextseq, -1)
                } else {
                  go(CP + 1, 1, subseq, CP)
                }
              }
              case x => {
                ans(x - '0') += 1
                x match {
                  case '0' => {
                    val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()
                    DP match{
                      case 1 => go(CP, DP, nextseq, -1)
                      case 0 => go(CP + DP, DP, nextseq, -1)
                    }
                  }

                  case y => {
                    val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, nextseq, CP)
                  }
                }
              }
            }
          }
        }
      } else {
        for (it <- ans) System.out.print(it + " ")
        System.out.println()
      }
    }

    go(0, 1, seq, -1)
  }
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val q = cin.nextInt()
    val s = cin.next()

    for (i <- 0 until q) {
      val l = cin.nextInt()
      val r = cin.nextInt()
      val seq = s.subSequence(l - 1, r).toString()
      SolveSubTask(seq)
    }

  }
}

object CodeForces {

  def SolveSubTask(seq: java.lang.String) {
    val ans = new Array[Int](10)
    def go(CP: Int, DP: Int, subseq: java.lang.String, pos: Int) { // DP 1 right -1 left
      val len = subseq.length()
      if (CP >= 0 && CP < len) {
        pos match {
          case -1 => {
            subseq.charAt(CP) match {
              case '<' => go(CP - 1, -1, subseq, CP)
              case '>' => go(CP + 1, 1, subseq, CP)
              case x => {
                ans(x - '0') += 1
                x match {
                  case '0' => {
                    val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()

                    go(CP + DP, DP, nextseq, CP)
                  }
                  case y => {
                    val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, subseq, CP)
                  }
                }
              }
            }
          }
          case others => {
            subseq.charAt(CP) match {
              case '<' => {
                if (!subseq.charAt(pos).isDigit) {
                  val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()
                  go(CP - 1, -1, nextseq, CP)
                } else {
                  go(CP - 1, -1, subseq, CP)
                }
              }
              case '>' => {
                if (!subseq.charAt(pos).isDigit) {
                  val nextseq = subseq.subSequence(0, pos).toString() + subseq.subSequence(pos + 1, subseq.length()).toString()
                  go(CP + 1, 1, nextseq, CP)
                } else {
                  go(CP + 1, 1, subseq, CP)
                }
              }
              case x => {
                ans(x - '0') += 1
                x match {
                  case '0' => {
                    val nextseq = subseq.subSequence(0, CP).toString() + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, nextseq, CP)
                  }

                  case y => {
                    val nextseq = subseq.subSequence(0, CP).toString() + (x - 1).toChar + subseq.subSequence(CP + 1, subseq.length()).toString()
                    go(CP + DP, DP, nextseq, CP)
                  }
                }
              }
            }
          }
        }
      } else {
        for (it <- ans) System.out.print(it + " ")
        System.out.println()
      }
    }

    go(0, 1, seq, -1)
  }
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val q = cin.nextInt()
    val s = cin.next()

    for (i <- 0 until q) {
      val l = cin.nextInt()
      val r = cin.nextInt()
      val seq = s.subSequence(l - 1, r).toString()
      SolveSubTask(seq)
    }

  }
}

object Olymp{
  def main(args: Array[String]): Unit = {
	val Array(n, q) = readLine.split(' ').map(Integer.parseInt(_))
	val s = readLine.toList
	for (i <- 1 to q) {
	  val Array(l, r) = readLine.split(' ').map(Integer.parseInt(_))
	  solve(Nil, s.drop(l-1).take(r-l+1), '>', Vector.fill(10)(0))
	}
  }

  def solve(prev: List[Char], cur: List[Char], dir: Char, cnt: Vector[Int]): Unit = (prev, cur, dir) match {
    case (_, '0' :: xs, '>') => solve(prev, xs, '>', cnt.updated(0, cnt(0)+1))
    case (y :: ys, '0' :: xs, '<') => solve(ys, y :: xs, '<', cnt.updated(0, cnt(0) + 1))
    case (_, x :: xs, '>') if x.isDigit => solve((x-1).toChar :: prev, xs, '>', cnt.updated(x - '0', cnt(x - '0')+1))
    case (y :: ys, x :: xs, '<') if x.isDigit => solve(ys, y :: (x-1).toChar :: xs, '<', cnt.updated(x - '0', cnt(x - '0') + 1))
    case (_, '>' :: x :: xs, _) if !x.isDigit => solve(prev, x :: xs, '>', cnt)
    case (y :: ys, '<' :: xs, _) if !y.isDigit => solve(ys, y :: xs, '<', cnt)
    case (_, '>' :: xs, _) => solve('>' :: prev, xs, '>', cnt)
    case (y :: ys, '<' :: xs, _) => solve(ys, y :: '<' :: xs, '<', cnt)
    case _ => for { i <- cnt } print(i + " "); println
  }
}


Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 50$$$) — the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.

In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.

9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji

NoteIn the first example, "battab" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string.

import collection.mutable.HashMap

object Main {
  def main(args: Array[String]) = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val a = Array.tabulate(n)((_) => readLine)
    val x = f1(a)
    println(x.length)
    println(x)
  }
  def f1(a: Array[String]): String = {
    val f = HashMap[String, Int]()
    val b = HashMap[String, Int]()
    a.indices.foreach((i) => {
      if (a(i) == a(i).reverse) b.update(a(i), b.getOrElse(a(i), 0) + 1)
      a.indices.foreach((j) =>
        if (i != j && a(i) == a(j).reverse) {
          f.update(a(i), f.getOrElse(a(i), 0) + 1)
        }
      )
    })
    var pre = ""
    var post = ""
    while (f.size != 0) {
      val x = f.keySet.head
      val y = x.reverse
      val k = Math.min(f(x), f(y))
      pre = pre + (x * k)
      post = (y * k) + post
      if (b.contains(x)) {
        b.update(x, b(x) - k)
      }
      if (b.contains(y)) {
        b.update(y, b(y) - k)
      }
      f.remove(x)
      f.remove(y)
    }
    b.find { case (k, v) => v > 0 } match {
      case None         => pre + post
      case Some((k, v)) => pre + k + post
    }
  }
}


One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.

The first line contains five non-negative integers NS, NM, NL, NXL, NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1 ≤ K ≤ 1000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS + NM + NL + NXL + NXXL ≥ K.

For each contestant, print a line containing the size of the T-shirt he/she got.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(' ').map(_.toInt)
  val n = in.next().toInt
  val map = List("S", "M", "L", "XL", "XXL").zipWithIndex.toMap
  val mapReverse = map.map(i => i._2 -> i._1)
  val res = (1 to n).map(_ => in.next()).map {
    case v if data(map(v)) != 0 =>
      data(map(v)) -= 1
      v
    case v if map(v) != 4 && data(map(v) + 1) != 0 =>
      data(map(v) + 1) -= 1
      mapReverse(map(v) + 1)
    case v if map(v) != 0 && data(map(v) - 1) != 0 =>
      data(map(v) - 1) -= 1
      mapReverse(map(v) - 1)
    case v if map(v) < 3 && data(map(v) + 2) != 0 =>
      data(map(v) + 2) -= 1
      mapReverse(map(v) + 2)
    case v if map(v) > 1 && data(map(v) - 2) != 0 =>
      data(map(v) - 2) -= 1
      mapReverse(map(v) - 2)
    case v if map(v) < 2 && data(map(v) + 3) != 0 =>
      data(map(v) + 3) -= 1
      mapReverse(map(v) + 3)
    case v if map(v) > 2 && data(map(v) - 3) != 0 =>
      data(map(v) - 3) -= 1
      mapReverse(map(v) - 3)
    case v if map(v) < 1 && data(map(v) + 4) != 0 =>
      data(map(v) + 4) -= 1
      mapReverse(map(v) + 4)
    case v if map(v) > 3 && data(map(v) - 4) != 0 =>
      data(map(v) - 4) -= 1
      mapReverse(map(v) - 4)
  }
  println(res.mkString("\n"))
}


You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$.    An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$.    An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.

In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.

NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow):  first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices;  the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion;  then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it;  the vertex $$$4$$$ will be connected with the vertex $$$3$$$;  then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth);  you will just delete the vertex $$$4$$$;  there are no more vertices to delete.   In the second example you don't need to delete any vertex:  vertices $$$2$$$ and $$$3$$$ have children that respect them;  vertices $$$4$$$ and $$$5$$$ respect ancestors.   In the third example the tree will change this way:

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

object C extends App {
  val n = readInt

  val p = Array.ofDim[Int](n)
  val c = Array.ofDim[Boolean](n)

  for (i <- 0 until n) {
    val Array(pi, ci) = readInts
    p(i) = pi - 1
    c(i) = ci == 1
  }

  val bad = c.clone
  for (i <- 0 until n) {
    if (!c(i) && p(i) >= 0)
      bad(p(i)) = false
  }

  var nothing = true
  for (i <- 1 to n) {
    if (bad(i-1)) {
      print(s"$i ")
      nothing = false
    }
  }
  if (nothing)
    println(-1)
  else
    println()

  def readInts() = readLine.split(" ").map(_.toInt)
}

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 java.util.Arrays

  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 = ni()
    val (p, c) = na2(N)

    val revP = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())
    REP(N) { i =>
      if (p(i) != -1) revP(p(i) - 1) += i
    }

    debug(revP.mkString(","))

    val del = Array.ofDim[Boolean](N)
    REP(N) { i =>
      if (p(i) != -1 && c(i) == 1 && revP(i).forall(j => c(j) == 1)) {
        del(i) = true
      }
    }

    val ans = del.zipWithIndex.filter(_._1).map(_._2 + 1)
    if (ans.isEmpty) out.println(-1)
    else out.println(ans.mkString(" "))
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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