You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any.

//package codeforces.contests._1399

object BinaryStringToSubsequences {
  def main(args: Array[String]): Unit = {
    for (t <- 1 to io.StdIn.readInt) {
      val _ = io.StdIn.readInt()
      val input = io.StdIn.readLine.toList

      var id = 0

      def getUniqueId: Int = {
        id += 1
        id
      }

      @scala.annotation.tailrec
      def loop(ls: List[Char], zeroIds: List[Int] = Nil, oneIds: List[Int] = Nil, result: List[Int] = Nil): List[Int] = {
        ls match {
          case Nil => result.reverse
          case '0' :: tail => oneIds match {
            case Nil =>
              val id = getUniqueId
              loop(tail, id :: zeroIds, Nil, id :: result)
            case id :: oneTail =>
              loop(tail, id :: zeroIds, oneTail, id :: result)
          }
          case '1' :: tail => zeroIds match {
            case Nil =>
              val id = getUniqueId
              loop(tail, Nil, id :: oneIds, id :: result)
            case id :: zeroTail =>
              loop(tail, zeroTail, id :: oneIds, id :: result)
          }
        }
      }

      println {
        val ans = loop(input)
        s"$id\n${ans.mkString(" ")}"
      }
    }
  }
}

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

object BinaryStringToSubsequences1399D extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//          val lines: Iterator[String] =
//            Source.fromString("1\n5\n11000\n1\n1\n2\n00\n2\n10\n2\n01\n2\n11\n3\n000\n3\n100\n3\n010\n3\n110\n3\n001\n3\n101\n3\n011\n3\n111\n4\n0000\n4\n1000\n4\n0100\n4\n1100\n4\n0010\n4\n1010\n4\n0110\n4\n1110\n4\n0001\n4\n1001\n4\n0101\n4\n1101\n4\n0011\n4\n1011\n4\n0111\n4\n1111\n5\n00000\n5\n10000\n5\n01000\n5\n11000\n5\n00100\n5\n10100\n5\n01100\n5\n11100\n5\n00010\n5\n10010\n5\n01010\n5\n11010\n5\n00110\n5\n10110\n5\n01110\n5\n11110\n5\n00001\n5\n10001\n5\n01001\n5\n11001\n5\n00101\n5\n10101\n5\n01101\n5\n11101\n5\n00011").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { case (ar, max) =>
    println(max)
    println(ar mkString " ")
  }

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      (Array(1),1)
    } else {
      val s = lines.next.toCharArray
      solve(s)
    }
  }

  private def solve(s: Array[Char]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val ones = mutable.Stack[Int]()
    val zeros = mutable.Stack[Int]()
    def updGroup(v: Char, gr: Int) = v match {
      case '0' => zeros push gr
      case '1' => ones push gr
    }
    updGroup(s.head, 1)
    def findFirstAvailable(lastVal: Char) = lastVal match {
      case '0' => if (ones.isEmpty) None else Some(ones.pop)
      case '1' => if (zeros.isEmpty) None else Some(zeros.pop)
    }
    def removeGroupOfPrevSet(v: Char): Unit = v match {
      case '0' => ones.pop
      case '1' => zeros.pop
    }
    var cg = 1
    var largestG = 1
    var i = s.head
    for (j <- s.tail) {
      if (i == j) {
        cg = findFirstAvailable(j).getOrElse({
          largestG = largestG + 1
          largestG
        })
        sol += cg
      }
      else {
        removeGroupOfPrevSet(j)
        sol += cg
      }
      updGroup(j, cg)
      i = j
    }
    (sol.toArray, largestG)
  }
}

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

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

    val t = StdIn.readLine().toInt

    for (_ <- 1 to t) {
      val n = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      var cnt = 1
      val res = Array.fill(str.length)(0)
      val q0, q1 = mutable.Queue[Int]()

      for (i <- 0 until n) {
        if (str(i) == '0') {
          if (q1.isEmpty) {
            res(i) = cnt
            cnt += 1
          } else {
            res(i) = res(q1.dequeue())
          }
          q0.enqueue(i)
        } else {
          if (q0.isEmpty) {
            res(i) = cnt
            cnt += 1
          } else {
            res(i) = res(q0.dequeue())
          }
          q1.enqueue(i)
        }
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}

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

object BinaryStringToSubsequences1399D extends App {

//  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
          val lines: Iterator[String] =
            Source.fromString("1\n5\n11000\n1\n1\n2\n00\n2\n10\n2\n01\n2\n11\n3\n000\n3\n100\n3\n010\n3\n110\n3\n001\n3\n101\n3\n011\n3\n111\n4\n0000\n4\n1000\n4\n0100\n4\n1100\n4\n0010\n4\n1010\n4\n0110\n4\n1110\n4\n0001\n4\n1001\n4\n0101\n4\n1101\n4\n0011\n4\n1011\n4\n0111\n4\n1111\n5\n00000\n5\n10000\n5\n01000\n5\n11000\n5\n00100\n5\n10100\n5\n01100\n5\n11100\n5\n00010\n5\n10010\n5\n01010\n5\n11010\n5\n00110\n5\n10110\n5\n01110\n5\n11110\n5\n00001\n5\n10001\n5\n01001\n5\n11001\n5\n00101\n5\n10101\n5\n01101\n5\n11101\n5\n00011").getLines
  val ntc: Int = lines.next.toInt
  (0 until ntc map { _ =>
    handleTC()
  }).zipWithIndex.foreach({ case(ar,i) =>
    //      println(s"# $i")
    println(ar.max)
    println(ar mkString " ")
  })

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("")
      solve(s)
    }
  }

  private def solve(s: Array[String]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.Map[Int, String](1 -> s.head)
    def findLeastDiff(lastVal: String) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    var largestG = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse({
          largestG = largestG + 1
          largestG
        })
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

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

object BinaryStringToSubsequences1399D extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//        val lines: Iterator[String] =
//          Source.fromString("4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { ar =>
    println(ar.max)
    println(ar mkString " ")
  }

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("").map(_ == "1")
      solve(s)
    }
  }

  private def solve(s: Array[Boolean]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)
    def findLeastDiff(lastVal: Boolean) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse(cg + 1)
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

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

object BinaryStringToSubsequences1399D extends App {

//  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
        val lines: Iterator[String] =
          Source.fromString("4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { ar =>
    println(ar.max)
    println(ar mkString " ")
  }

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("").map(_ == "1")
      solve(s)
    }
  }

  private def solve(s: Array[Boolean]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)
    def findLeastDiff(lastVal: Boolean) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse(cg + 1)
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

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

object BinaryStringToSubsequences1399D extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//        val lines: Iterator[String] =
//          Source.fromString("1\n5\n11000\n1\n1\n2\n00\n2\n10\n2\n01\n2\n11\n3\n000\n3\n100\n3\n010\n3\n110\n3\n001\n3\n101\n3\n011\n3\n111\n4\n0000\n4\n1000\n4\n0100\n4\n1100\n4\n0010\n4\n1010\n4\n0110\n4\n1110\n4\n0001\n4\n1001\n4\n0101\n4\n1101\n4\n0011\n4\n1011\n4\n0111\n4\n1111\n5\n00000\n5\n10000\n5\n01000\n5\n11000\n5\n00100\n5\n10100\n5\n01100\n5\n11100\n5\n00010\n5\n10010\n5\n01010\n5\n11010\n5\n00110\n5\n10110\n5\n01110\n5\n11110\n5\n00001\n5\n10001\n5\n01001\n5\n11001\n5\n00101\n5\n10101\n5\n01101\n5\n11101\n5\n00011").getLines
  val ntc: Int = lines.next.toInt
  (0 until ntc map { _ =>
    handleTC()
  }).zipWithIndex.foreach({ case(ar,i) =>
      println(s"# $i")
      println(ar.max)
      println(ar mkString " ")
    })

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("").map(_ == "1")
      solve(s)
    }
  }

  private def solve(s: Array[Boolean]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)
    def findLeastDiff(lastVal: Boolean) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse(groupLasts.size + 1)
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)
        temp += h.last - '0'
        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
            temp(li) = 1 ^ temp(li)
          } else {
            i = temp.length + 1
          }
        }
        s = t
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)
        temp += h.last - '0'
        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
          } else {
            i = temp.length + 1
          }
        }
        s = t
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)
        temp += h.last - '0'
        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
          } else {
            i = temp.length + 1
          }
        }
        s = t
      }
      println(res.mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)

        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
            temp(li) = 1 ^ temp(li)
          } else {

            i = res.max + 1
            temp += h.last - '0'
          }
        }

        s = t
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}


Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?Heidi's n friends are labeled 0 through n - 1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n - 1 pairs of friends who know each other directly.Jenny is given the number 0.

The first line of the input contains the number of friends n (3 ≤ n ≤ 100). The next n - 1 lines each contain three space-separated integers u, v and c (0 ≤ u, v ≤ n - 1, 1 ≤ c ≤ 104), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c. It is guaranteed that the social network of the input forms a tree.

Output a single integer – the maximum sum of costs.

NoteIn the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 2).

import java.util.StringTokenizer

import scala.collection.mutable

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

  read()
  val n = int()
  val linksBuilder = Array.fill(n)(mutable.ArrayBuilder.make[(Int, Int)])
  for (
    i <- 1 until n
  ) {
    read()
    val a = int()
    val b = int()
    val c = int()
    linksBuilder(a) += ((b, c))
    linksBuilder(b) += ((a, c))
  }
  val links = linksBuilder.map(_.result())

  def cost(cur: Int, prev: Int): Int = {
    val l = links(cur).filterNot(_._1 == prev)
    if (l.isEmpty) return 0
    l.map { case (next, c) =>
      c + cost(next, cur)
    }.max
  }

  println(cost(0, -1))
}


There is an integer $$$n$$$ without zeros in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns.On her turn, Alice must swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left.You have to find the smallest integer Alice can get in the end, if she plays optimally.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$10 \le n \le 10^9$$$) — the integer for the game. $$$n$$$ does not have zeros in its decimal representation.

For each test case output a single integer — the smallest integer Alice can get in the end of the game.

NoteIn the first test case Alice has to swap $$$1$$$ and $$$2$$$. After that Bob removes the last digit, $$$1$$$, so the answer is $$$2$$$.In the second test case Alice can swap $$$3$$$ and $$$1$$$: $$$312$$$. After that Bob deletes the last digit: $$$31$$$. Then Alice swaps $$$3$$$ and $$$1$$$: $$$13$$$ and Bob deletes $$$3$$$, so the answer is $$$1$$$.

import java.io.BufferedReader
import java.io.InputStreamReader

object Main {

  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextString()
      if (n.length > 2)
        System.out.println(n.min)
      else
        System.out.println(n.charAt(1))
    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

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

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

  }

}

object Main {
  import java.io.{BufferedReader, InputStreamReader}

  val x = 0
  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextString()
      if (n.length > 2)
        System.out.println(n.min)
      else
        System.out.println(n.charAt(1))
    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

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

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

  }

}

/*
https://codeforces.com/contest/1684/problem/0

1234 => 2134 => 213 => 312 => 31 => 13 => 1
1234 => 1324 => 132 => 123 => 12 => 21 => 2

1) 2d. XY => YX => Y
2) > 2d. XYZAm => XmZAY =>... => XmZ => ZmX => Zm => mZ

 */

import scala.io.StdIn

object many_digitals{

    def main(args: Array[String]): Unit = {
        def solving(n: String) = {
            if (n.length == 2) {
                println(n(1))
            }
            else {
                val answer = n.split("").map(x => x.toInt).min
                println(answer)
            }
        }

        val t = StdIn.readLine().toInt
        val in = new Array[String](t)
        for (i <- 0 until(t)) {
            //        val n = StdIn.readLine().toInt
            in(i) = StdIn.readLine()
        }

        in.foreach(solving _)

    }
}


Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections.  Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).

The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.

For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.

NoteIn the example testcase:Here are the intersections used:    Intersections on the path are 3, 1, 2 and 4.  Intersections on the path are 4, 2 and 1.  Intersections on the path are only 3 and 6.  Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94.  Intersections on the path are 6, 3 and 1.  Intersections on the path are 3 and 7. Passing fee of the road between them is 0.  Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).

import scala.collection._

object Main {

    var map = mutable.Map[Long, Long]().withDefaultValue(0L)

    def main(args: Array[String]): Unit = {
        var Q = readInt()
        for(_ <- 0 until Q) {

            val a: Array[Long] = readLine().split(" ").map(_.toLong)

            val u: Long = a(1)
            val v: Long = a(2)

            val lca: Long = LCA(u, v)

            if (a(0) == 1) {
                val cost: Long = a(3)
                update(u, lca, cost)
                update(v, lca, cost)
            } else {
                val ret = getCost(u, lca, 0) + getCost(v, lca, 0)
                println(ret)
            }
        }
    }

    @annotation.tailrec
    def LCA(u: Long, v: Long): Long = {
        if (u == v) v
        else if (u > v) LCA(u / 2, v)
        else LCA(u, v / 2)
    }

    @annotation.tailrec
    def update(v: Long, lca: Long, cost: Long) {
        if (v > lca) {
            map(v) += cost
            update(v / 2, lca, cost)
        }
    }

    @annotation.tailrec
    def getCost(v: Long, lca: Long, acc: Long): Long = {
        if (v > lca) {
            map.get(v) match {
                case Some(cost) => getCost(v / 2, lca, acc + cost)
                case None => getCost(v / 2, lca, acc)
            }
        } else acc
    }
}

import scala.collection._

object Main {

    var map = mutable.Map[Long, Long]().withDefaultValue(0L)

    def main(args: Array[String]): Unit = {
        var Q = readInt()
        for(_ <- 0 until Q) {

            val a: Array[Long] = readLine().split(" ").map(_.toLong)

            val u: Long = a(1)
            val v: Long = a(2)

            val lca: Long = LCA(u, v)

            if (a(0) == 1) {
                val cost: Long = a(3)
                update(u, lca, cost)
                update(v, lca, cost)
            } else {
                val ret = getCost(u, lca, 0) + getCost(v, lca, 0)
                println(ret)
            }
        }
    }

    @annotation.tailrec
    def LCA(u: Long, v: Long): Long = {
        if (u == v) v
        else if (u > v) LCA(u / 2, v)
        else LCA(u, v / 2)
    }

    @annotation.tailrec
    def update(v: Long, lca: Long, cost: Long) {
        if (v > lca) {
            map(v) += cost
            update(v / 2, lca, cost)
        }
    }

    // @annotation.tailrec
    def getCost(v: Long, lca: Long, acc: Long): Long = {
        if (v > lca) {
            map.get(v).map(x => getCost(v / 2, lca, acc + x)).getOrElse(getCost(v / 2, lca, acc))
            // map.get(v) match {
            //     case Some(cost) => getCost(v / 2, lca, acc + cost)
            //     case None => getCost(v / 2, lca, acc)
            // }
        } else acc
    }
}

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

object Main extends App {

    var map = mutable.Map[Long, Long]().withDefaultValue(0L)

    var Q = IO.nextInt
    (0 until Q).foreach { _ =>

      val (kindOf, u, v) = (IO.nextLong, IO.nextLong, IO.nextLong)
      val lca: Long = LCA(u, v)

      if (kindOf == 1) {
          val cost: Long = IO.nextLong
          update(u, lca, cost)
          update(v, lca, cost)
      } else {
          val ret = getCost(u, lca, 0) + getCost(v, lca, 0)
          println(ret)
      }
    }

    IO.close

    @annotation.tailrec
    def LCA(u: Long, v: Long): Long = {
        if (u == v) v
        else if (u > v) LCA(u / 2, v)
        else LCA(u, v / 2)
    }

    @annotation.tailrec
    def update(v: Long, lca: Long, cost: Long) {
        if (v > lca) {
            map(v) += cost
            update(v / 2, lca, cost)
        }
    }

    def getCost(v: Long, lca: Long, acc: Long): Long = {
      if (v > lca) map.get(v).map(x => getCost(v / 2, lca, acc + x)).getOrElse(getCost(v / 2, lca, acc))
      else acc
    }
}

object IO {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)
  var tok = new StringTokenizer("")
  def nextToken() = {
    while (!tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine())
    }
    tok.nextToken()
  }

  def nextInt = nextToken().toInt
  def nextLong = nextToken().toLong
  def println(a: Any) = out.println(a)
  def close = {
    in.close()
    out.close()
  }
}

import java.util.Scanner
import scala.collection._
import java.lang.Math._

/**
  * @author antipov.
  *         15.07.2016 14:47.
  */
object A extends App {
  val sc: Scanner = new Scanner(System.in)
  def readInt(): Int = sc.nextInt()
  def readLong(): Long = sc.nextLong()

  case class Edge(from: Long, to: Long) {
    require(from <= to)

    override def hashCode(): Int = {
      val prime = 31
      (prime + from.hashCode()) * prime + to.hashCode()
    }

    override def equals(obj: scala.Any): Boolean = obj match {
      case Edge(x, y) => x == from && y == to
      case _ => false
    }

    override def toString: String = "Edge(" + from + ", " + to + ")"
  }

  val q = sc.nextInt()
  val added = new mutable.HashMap[Edge, Long]() withDefaultValue 0L

  (0 until q).foreach(i => {
    val (t, v, u) = (readLong(), readLong(), readLong())
    val edges = convert(path(v, u))
    if(t == 1) {
      val w = readLong()
      edges foreach(e => added += ((e, added(e) + w)))
    } else
      println(edges map (e => added(e)) sum)
  })

  def convert(path: List[Long]): List[Edge] = {
    def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {
      case List(x) => acc
      case x :: y :: xs => convert(path.tail, Edge(min(x, y), max(x, y)) :: acc)
    }
    convert(path, Nil)
  }

  def path(v: Long, u: Long): List[Long] = {
    def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {
      if(v == u) accU.reverse ::: (v :: accV)
      else if(v > u) path(v / 2, u, v :: accV, accU)
      else path(v, u / 2, accV, u :: accU)
    }
    path(v, u, List(), List())
  }

}

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

import scala.collection.immutable.TreeMap

/**
  * @author antipov.
  *         15.07.2016 14:47.
  */
object A extends App {
  object Reader {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(System.out)
  }

  val sc: Scanner = new Scanner(System.in)
  def readInt(): Int = sc.nextInt()
  def readLong(): Long = sc.nextLong()

  case class Edge(var from: Long, var to: Long) extends Comparable[Edge] {
    if(from > to) {
      val tmp = from
      from = to
      to = tmp
    }

    override def compareTo(o: Edge): Int =
      if (this.from != o.from) this.from compareTo o.from
      else this.to compareTo o.to

    override def toString: String = "Edge(" + from + ", " + to + ")"
  }

  val q = sc.nextInt()
  var added = new TreeMap[Edge, Long]() withDefaultValue 0L

  (0 until q).foreach(i => {
    val (t, v, u) = (readLong(), readLong(), readLong())
    val edges = convert(path(v, u))
    if(t == 1) {
      val w = readLong()
      edges foreach(e => added = added + (e -> (added(e) + w)))
    } else
      println(edges map (e => added(e)) sum)
  })

  def convert(path: List[Long]): List[Edge] = {
    def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {
      case List(x) => acc
      case x :: y :: xs => convert(path.tail, Edge(x, y) :: acc)
    }
    convert(path, Nil)
  }

  def path(v: Long, u: Long): List[Long] = {
    def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {
      if(v == u) accU.reverse ::: (v :: accV)
      else if(v > u) path(v / 2, u, v :: accV, accU)
      else path(v, u / 2, accV, u :: accU)
    }
    path(v, u, List(), List())
  }
}

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

/**
  * @author antipov.
  *         15.07.2016 14:47.
  */
object A extends App {
  def readInt(): Int = IO.nextInt
  def readLong(): Long = IO.nextLong
  def println(a: Any) = IO.println(a)

  case class Edge(var from: Long, var to: Long) extends Comparable[Edge] {
    if(from > to) {
      val tmp = from
      from = to
      to = tmp
    }

    override def compareTo(o: Edge): Int =
      if (this.from != o.from) this.from compareTo o.from
      else this.to compareTo o.to

    override def toString: String = "Edge(" + from + ", " + to + ")"
  }

  val q = readInt
  var added = new immutable.TreeMap[Edge, Long]() withDefaultValue 0L

  (0 until q).foreach(i => {
    val (t, v, u) = (readLong, readLong, readLong)
    val edges = convert(path(v, u))
    if(t == 1) {
      val w = readLong
      edges.map (e => added = added + (e -> (added(e) + w)))
    } else
      println(edges map (e => added(e)) sum)
  })

  def convert(path: List[Long]): List[Edge] = {
    def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {
      case List(x) => acc
      case x :: y :: xs => convert(path.tail, Edge(x, y) :: acc)
    }
    convert(path, Nil)
  }

  def path(v: Long, u: Long): List[Long] = {
    def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {
      if(v == u) accU.reverse ::: (v :: accV)
      else if(v > u) path(v / 2, u, v :: accV, accU)
      else path(v, u / 2, accV, u :: accU)
    }
    path(v, u, List(), List())
  }

  IO.close
}

object IO {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)
  var tok = new StringTokenizer("")
  def nextToken() = {
    while (!tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine())
    }
    tok.nextToken()
  }

  def nextInt = nextToken().toInt
  def nextLong = nextToken().toLong
  def println(a: Any) = out.println(a)
  def close = {
    in.close()
    out.close()
  }
}

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

/**
  * @author antipov.
  *         15.07.2016 14:47.
  */
object A extends App {
  def readInt(): Int = IO.nextInt
  def readLong(): Long = IO.nextLong
  def println(a: Any) = IO.println(a)

  case class Edge(var from: Long, var to: Long) extends Comparable[Edge] {
    if(from > to) {
      val tmp = from
      from = to
      to = tmp
    }

    override def compareTo(o: Edge): Int =
      if (this.from != o.from) this.from compareTo o.from
      else this.to compareTo o.to

    override def toString: String = "Edge(" + from + ", " + to + ")"
  }

  val q = readInt
  var added = new immutable.TreeMap[Edge, Long]() withDefaultValue 0L

  (0 until q).foreach(i => {
    val (t, v, u) = (readLong, readLong, readLong)
    val edges = convert(path(v, u))
    if(t == 1) {
      val w = readLong
      edges foreach (e => added = added + (e -> (added(e) + w)))
    } else
      println(edges map (e => added(e)) sum)
  })

  def convert(path: List[Long]): List[Edge] = {
    def convert(path: List[Long], acc: List[Edge]): List[Edge] = path match {
      case List(x) => acc
      case x :: y :: xs => convert(path.tail, Edge(x, y) :: acc)
    }
    convert(path, Nil)
  }

  def path(v: Long, u: Long): List[Long] = {
    def path(v: Long, u: Long, accV: List[Long], accU: List[Long]): List[Long] = {
      if(v == u) accU.reverse ::: (v :: accV)
      else if(v > u) path(v / 2, u, v :: accV, accU)
      else path(v, u / 2, accV, u :: accU)
    }
    path(v, u, List(), List())
  }

  IO.close
}

object IO {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)
  var tok = new StringTokenizer("")
  def nextToken() = {
    while (!tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine())
    }
    tok.nextToken()
  }

  def nextInt = nextToken().toInt
  def nextLong = nextToken().toLong
  def println(a: Any) = out.println(a)
  def close = {
    in.close()
    out.close()
  }
}

object Lorenzo {
    import io.StdIn.readLine
    import collection.mutable.ArrayBuffer
    var map = collection.mutable.HashMap[Long, Long]()

    def main(args: Array[String]){
        var price = 0L

        for(i <- 0 until readLine.trim.toInt){
            val ar = readLine.trim.split(" ")

            var al = ar.tail.map(_.toLong)
            if(ar(0) == "1")
            {

                var v = al(0)
                var u = al(1)
                var w = al(2)
                var path = getPath(v, u)
                updateMap(path, w)
                price+=getPrice(path)

            }
            else
            {
                var v = al(0)
                var u = al(1)
                var path = getPath(v, u)
                updateMap(path, 0L)
                println(getPrice(path))

            }

        }

    }

    def depth(v: Long): Long = {
        v.toBinaryString.length
    }

    def getPath(v: Long, u: Long): ArrayBuffer[Long] = {
        var ab = ArrayBuffer[Long]()

        var nv = v
        var nu = u

        val dv = depth(v)
        val du = depth(u)

        if(dv > du)
        {
            for(i <- 0 until (dv - du).toInt)
            {
                ab+=nv
                nv/=2
            }

        }
        if(dv < du)
        {
            for(i <- 0 until (du - dv).toInt)
            {
                ab+=nu
                nu/=2
            }

        }

        while(nv != nu)
        {
            ab+=nv
            ab+=nu
            nv/=2
            nu/=2
        }

        ab
    }

    def updateMap(ab: ArrayBuffer[Long], p: Long): Unit = {
        for(i <- ab)
        {
            if(map.isDefinedAt(i))
            {
                map(i)+=p
            }
            else
            {
                map(i) = p
            }
        }

    }

    def getPrice(ab: ArrayBuffer[Long]): Long = {
        ab.fold(0L){ (z, i) =>
            z + map(i)
        }

    }

}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _697C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val costToParent = map[Long] to 0L

    @tailrec
    def increase(u: Long, v: Long, w: Long): Unit = {
      //debug(u, v, w)
      if (u > v) {
        costToParent(u) += w
        increase(u/2, v, w)
      } else if (u < v) {
        costToParent(v) += w
        increase(u, v/2, w)
      }
    }

    @tailrec
    def calc(u: Long, v: Long, acc: Long): Long = {
      if(u > v) {
        calc(u/2, v, acc + costToParent(u))
      } else if (v > u) {
        calc(u, v/2, acc + costToParent(v))
      } else {
        acc
      }
    }

    repeat(read[Int]) {
      read[Int] match {
        case 1 =>
          val v, u, w = read[Long]
          increase(u, v, w)
        case 2 =>
          val v, u = read[Long]
          val cost = calc(u, v, 0L)
          write(cost).writeLine()
      }
    }
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


This is the easy version of the problem. In this version, $$$n \le 3000$$$, $$$x \ge y$$$ holds. You can make hacks only if both versions of the problem are solved.You are given two binary strings $$$a$$$ and $$$b$$$, both of length $$$n$$$. You can do the following operation any number of times (possibly zero).   Select two indices $$$l$$$ and $$$r$$$ ($$$l < r$$$).  Change $$$a_l$$$ to $$$(1 - a_l)$$$, and $$$a_r$$$ to $$$(1 - a_r)$$$.  If $$$l + 1 = r$$$, the cost of the operation is $$$x$$$. Otherwise, the cost is $$$y$$$. You have to find the minimum cost needed to make $$$a$$$ equal to $$$b$$$ or say there is no way to do so.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 600$$$) — the number of test cases. Each test case consists of three lines. The first line of each test case contains three integers $$$n$$$, $$$x$$$, and $$$y$$$ ($$$5 \le n \le 3000$$$, $$$1 \le y \le x \le 10^9$$$) — the length of the strings, and the costs per operation. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. The third line of each test case contains the string $$$b$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3000$$$.

For each test case, if there is no way to make $$$a$$$ equal to $$$b$$$, print $$$-1$$$. Otherwise, print the minimum cost needed to make $$$a$$$ equal to $$$b$$$.

NoteIn the first test case, selecting indices $$$2$$$ and $$$3$$$ costs $$$8$$$, which is the minimum possible cost.In the second test case, we cannot make $$$a$$$ equal to $$$b$$$ using any number of operations.In the third test case, we can perform the following operations:  Select indices $$$3$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0101011 now.  Select indices $$$4$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0100001 now. The total cost is $$$6$$$.In the fourth test case, we don't have to perform any operations.

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
   val input = readLine().split(" ").map(_.toInt)
   val (n, x, y) = (input(0), input(1), input(2))
   val a = readLine().map(_ == '1')
   val b = readLine().map(_ == '1')
   val diffs = a.zip(b).zip(for(i <- 1 to n) yield i).filter{case ((ai, bi), i) => ai != bi}.map(_._2)
   if(diffs.length % 2 == 1)
    println(-1)
  else if(diffs.length == 2 && diffs(0) + 1 == diffs(1)) {
    if(y * 2 <= x)
      println(2*y)
    else
      println(x)
  } else println(y.toLong * diffs.length.toLong / 2)

  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
   val input = readLine().split(" ").map(_.toInt)
   val (n, x, y) = (input(0), input(1), input(2))
   val a = readLine().map(_ == '1')
   val b = readLine().map(_ == '1')
   val diffs = a.zip(b).zip(for(i <- 1 to n) yield i).filter{case ((ai, bi), i) => ai != bi}.map(_._2)
   if(diffs.length % 2 == 1)
    println(-1)
  else if(diffs.length == 2 && diffs(0) + 1 == diffs(1)) {
    if(y * 2 <= x)
      println(2*y)
    else
      println(x)
  } else println(y * diffs.length / 2)

  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}


Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price.The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.  The presented order book says that someone wants to sell the product at price $$$12$$$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $$$10$$$. There are two possible actions in this orderbook:  Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL $$$20$$$" if there is already an offer "BUY $$$20$$$" or "BUY $$$25$$$" — in this case you just accept the best BUY offer.You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: "ADD $$$p$$$" denotes adding a new order with price $$$p$$$ and unknown direction. The order must not contradict with orders still not removed from the order book.  "ACCEPT $$$p$$$" denotes accepting an existing best offer with price $$$p$$$ and unknown direction.The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $$$10^9 + 7$$$. If it is impossible to correctly restore directions, then output $$$0$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 363\,304$$$) — the number of actions in the log. Each of the next $$$n$$$ lines contains a string "ACCEPT" or "ADD" and an integer $$$p$$$ ($$$1 \le p \le 308\,983\,066$$$), describing an action type and price.  All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.

Output the number of ways to restore directions of ADD actions modulo $$$10^9 + 7$$$.

6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3

7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5

NoteIn the first example each of orders may be BUY or SELL.In the second example the order with price $$$1$$$ has to be BUY order, the order with the price $$$3$$$ has to be SELL order.

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

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

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

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

  def solve(): Unit = {
    val N = ni()

    var ans = 1L
    val book = new java.util.TreeSet[Int]()
    var sell, buy = -1

    REP(N) { _ =>
      val token = ns()
      val p = ni()
      token match {
        case "ADD" => book.add(p)
        case "ACCEPT" =>
          if (sell != -1 && sell < p || buy != -1 && p < buy) {
            out.println(0)
            return
          }

          // まだ確定してないオーダーの場合だけ*2する
          if (p != sell && p != buy) ans = ans * 2 % MOD

          book.remove(p)

          val newSell = book.higher(p)
          sell = if (newSell > 0) newSell else -1
          val newBuy = book.lower(p)
          buy = if (newBuy > 0) newBuy else -1
      }
    }

    val it = book.iterator()
    var unknown = 0
    while(it.hasNext) {
      val p = it.next()
      if ((buy == -1 || buy < p) && (sell == -1 || p < sell)) unknown += 1
    }
    if (unknown > 0) ans = ans * (unknown + 1) % MOD

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    import java.util
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val orders = new util.TreeSet[Int]()
    var ans = 1L

    var h, l: Option[Int] = None
    rep(N) { _ =>
      val command = sc.next()
      val p = sc.nextInt()
      command match {
        case "ADD" => orders.add(p)
        case "ACCEPT" =>
          if (h.exists(p > _) || l.exists(p < _)) {
            out.println("0")
            return
          } else if (h.contains(p) || l.contains(p)){
            h = Option(orders.higher(p))
            l = Option(orders.lower(p))
            orders.remove(p)
          } else {
            h = Option(orders.higher(p))
            l = Option(orders.lower(p))
            ans = ans * 2 % MOD
            orders.remove(p)
          }
      }
    }

    val it = orders.iterator()
    while(it.hasNext) {
      val p = it.next()
      if (l.exists(p > _) && h.exists(p < _)) ans = ans * 2 % 2
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  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)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()

    var ans = 1L
    val book = new java.util.TreeSet[Int]()
    var sell, buy = -1

    REP(N) { _ =>
      val token = ns()
      val p = ni()
      token match {
        case "ADD" => book.add(p)
        case "ACCEPT" =>
          if (sell != -1 && sell <= p || buy != -1 && p <= buy) {
            out.println(0)
            return
          }

          // まだ確定してないオーダーの場合だけ*2する
          if (p != sell && p != buy) ans = ans * 2 % MOD

          book.remove(p)

          val newSell = book.higher(p)
          sell = if (newSell > 0) newSell else -1
          val newBuy = book.lower(p)
          buy = if (newBuy > 0) newBuy else -1
      }
    }

    val it = book.iterator()
    var unknown = 0
    while(it.hasNext) {
      val p = it.next()
      if ((buy == -1 || buy < p) && (sell == -1 || p < sell)) unknown += 1
    }
    if (unknown > 0) ans = ans * (unknown + 1) % MOD

    out.println(ans)
  }

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

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

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

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

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

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


Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".

The first line contains a non-empty string s, consisting of lowercase Latin letters — that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≤ k ≤ 13) — the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.

Print the single number — the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.

NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.

object A {
  def main(args: Array[String]) {
    val input = readLine
    val forbid = Map(((1 to readInt) map (_ => readLine)) flatMap (str => List(str(0) -> Some(str), str(1) -> Some(str))): _*) withDefaultValue None
    var currentPair: Option[String] = None
    var striked = 0
    var found = List(0, 0)
    for (c <- input) {
      forbid(c) match {
        case None => {
          currentPair = None
          striked += found.min
          found = List(0, 0)
        }
        case Some(str) => {
          val newFound = str.indexOf(c) match {
            case 0 => List(1, 0)
            case 1 => List(0, 1)
          }
          found = currentPair match {
            case Some(cur_str) => {
              if (str == cur_str) (found zip newFound) map (x => x._1 + x._2)
              else {
                striked += found.min
                currentPair = Some(str)
                newFound
              }
            }
            case None => {
              currentPair = Some(str)
              newFound
            }
          }
        }
      }
    }
    striked += (currentPair match {
      case None => 0
      case Some(str) => found.min
    })
    println(striked)
  }
}

import collection.mutable.MutableList

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 29.02.12
 * Time: 2:59
 * To change this template use File | Settings | File Templates.
 */
object C {
  def main(args: Array[String]) {
    val input = readLine
    val forbid = Map(((1 to readInt) map (_ => readLine)) flatMap (str => List(str(0) -> Some(str), str(1) -> Some(str))): _*) withDefaultValue None
    var currentPair: Option[String] = None
    var striked = 0
    var found = List(0, 0)
    for (c <- input) {
      forbid(c) match {
        case None => {
          currentPair = None
          striked += found.min
          found = List(0, 0)
        }
        case Some(str) => {
          val newFound = str.indexOf(c) match {
            case 0 => List(1, 0)
            case 1 => List(0, 1)
          }
          found = currentPair match {
            case Some(cur_str) => {
              if (str == cur_str) (found zip newFound) map (x => x._1 + x._2)
              else {
                striked += found.min
                currentPair = Some(str)
                newFound
              }
            }
            case None => {
              currentPair = Some(str)
              newFound
            }
          }
        }
      }
    }
    striked += (currentPair match {
      case None => 0
      case Some(str) => found.min
    })
    println(striked)
  }
}


Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.

The first line contains three integers n,x,y (1 ≤ n ≤ 105, 1 ≤ x, y ≤ 106) — the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1 ≤ ai ≤ 109) — the number of hits needed do destroy the i-th monster.

Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.

NoteIn the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1.

import scala.collection._

object D extends App {

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

  val Array(n, x, y) = readLongs(3)
  val as = Array.fill(n.toInt) { readLine.toInt }

  val perSecond = x + y
  val resolution = x * y
  val stepX = (resolution / x)
  val stepY = (resolution / y)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  var c = 0
  for (a <- as) {

    def can(ticks: Long) = ticks / stepX + ticks / stepY >= a

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) >>> 1
        if (can(mid)) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val ticks = binSearch(0, Long.MaxValue - 1) - 1
    val stepsX = ticks / stepX
    val stepsY = ticks / stepY
    //println(ticks, stepsX, stepsY)

    var remain = a - stepsX - stepsY
    if (remain <= 0) println("Both")
    else {
      var px = stepsX * stepX
      var py = stepsY * stepY
      while (remain > 0) {
        c += 1
        //println(remain, px, py, c)
        val dx = px + stepX
        val dy = py + stepY
        if (dx == dy) {
          remain -= 2
          px += stepX
          py += stepY
          if (remain <= 0) println("Both")
        } else if (dx < dy) {
          val steps = ((dy - px) / stepX - 1) max 1
          remain -= steps
          px += stepX * steps
          if (remain <= 0) println("Vanya")
        } else {
          val steps = ((dx - py) / stepY - 1) max 1
          remain -= steps
          py += stepY * steps
          if (remain <= 0) println("Vova")
        }
      }
    }
  }

  Console.flush
}

object D {
  def main(args: Array[String]) = {
    val data = readLine().split(' ').map(t => t.toInt)
    val n = data(0)
    val x: Long = data(1)
    val y: Long = data(2)
    //println(x, y, n)
    for (e <- (1 to n).map(_ => readLine().toLong)) {
      println(solve(e, x, y))
    }
  }
  def gcd(a: Long, b: Long): Long = if (a == 0) b else gcd(b % a, a)
  def lcm(a: Long, b: Long) = a * b / gcd(a, b)
  def findMin(e: Long, sx: Long, sy: Long, begin: Long, end: Long): Long = {
    val mid = (begin + end) / 2
    if (begin == end) begin
    else if (mid / sx + mid / sy >= e) findMin(e, sx, sy, begin, mid)
    else findMin(e, sx, sy, mid + 1, end)
  }
  def solve(e: Long, x: Long, y: Long): String = {
    val z = lcm(x, y)
    val stepx = z / x
    val stepy = z / y

    val m = findMin(e, stepx, stepy, 0, e * stepx)
    if (m % stepx == 0) {
      if (m % stepy == 0) "Both"
      else "Vanya"
    } else "Vova"
  }
}

import java.util.Scanner

object D extends App {
  def cnt(t: Long) = t / x + t / y

  def bs(s: Long) = {
    var l = s * x * y / (x + y)
    var r = 2 * s * (x max y)

    while (r - l > 1) {
      val p = (l + r) / 2

//      val z = Seq(l, p, r)

      cnt(p) match {
        case c if c < s => l = p + 1
        case _ => r = p
      }

//      Console.err.println(z + " -> " + (z map cnt) + " by " + (l, r))
    }

//    val z = Seq(l, r)
//    Console.err.println(z + " -> " + (z map cnt))

    if (cnt(l) == s) l else r
  } ensuring {
    r => {
      val c = cnt(r)
//      Console.err.println("answer: " + r)
      s <= c && c <= s + 1
    }
  }

  val sc = new Scanner(System.in)

  val n = sc.nextInt()
  val (x, y) = n(sc.nextLong(), sc.nextLong())

  def gcd(a: Long, b: Long): Long = if (b == 0) a.abs else gcd(b, a % b)
  def n(x: Long, y: Long) = {
    val g = gcd(x, y)
    (x / g, y / g)
  }

  for (i <- 1 to n) {
    val s = sc.nextLong()

    def decide(t: Long): String = (t % x == 0, t % y == 0) match {
      case (true, true) => "Both"
      case (true, false) => "Vova"
      case (false, true) => "Vanya"
      case _ => decide(t - 1)
    }
    val ans = decide(bs(s))

    Console.println(ans)
  }
}

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

import scala.util.Sorting

object Solution {
  val INF: Long = 1e18.toLong;
  var x: Long = 0
  var y: Long = 0

  def countHits(num: Long): Long = num / y + num / x

  def solve(in: FastScanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    x = in.nextLong()
    y = in.nextLong()
    for (i <- 0 until n) {
      val a: Long = in.nextLong()
      var low: Long = 0
      var high: Long = INF
      while (high - low > 1) {
        val mid: Long = (low + high) / 2
        if (countHits(mid) >= a)
          high = mid
        else
          low = mid
      }
      if (high % y == 0 && high % x == 0)
        out.println("Both")
      else if (high % y == 0)
        out.println("Vanya")
      else
        out.println("Vova")
    }
  }

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

  class FastScanner(val in: InputStream) {
    var st: StringTokenizer = null
    var br = new BufferedReader(new InputStreamReader(in))

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

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

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

    def close(): Unit = {
      br.close()
    }
  }

}

import scala.collection._

object D extends App {

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

  val Array(n, x, y) = readLongs(3)
  val as = Array.fill(n.toInt) { readLine.toInt }

  val perSecond = x + y
  val resolution = BigInt(x * y)

  for (a <- as) {
    var remain = a % perSecond
    //if (remain < 0) remain += perSecond
   // println(remain)
    if (remain <= 0) println("Both")
    else {
      var px, py = 0L
      while (remain > 0) {
        val dx = (px + 1) * resolution / x
        val dy = (py + 1) * resolution / y
        if (dx == dy) {
          remain -= 2
          if (remain <= 0) println("Both")
        } else if (dx < dy) {
          remain -= 1
          px += 1
          if (remain <= 0) println("Vanya")
        } else {
          remain -= 1
          py += 1
          if (remain <= 0) println("Vova")
        }
      }
    }
  }
}

import scala.collection._

object D extends App {

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

  val Array(n, x, y) = readInts(3)
  val as = Array.fill(n) { readLine.toInt }

  val perSecond = x + y
  val resolution = x * y

  for (a <- as) {
    var remain = a % perSecond
    if (remain == 0) println("Both")
    else {
      var px, py = 0L
      while (remain > 0) {
        val dx = (px + 1) * resolution / x
        val dy = (py + 1) * resolution / y
        if (dx == dy) {
          remain -= 2
          if (remain <= 0) println("Both")
        } else if (dx < dy) {
          remain -= 1
          px += 1
          if (remain <= 0) println("Vanya")
        } else {
          remain -= 1
          py += 1
          if (remain <= 0) println("Vova")
        }
      }
    }
  }
}

import scala.collection._

object D extends App {

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

  val Array(n, x, y) = readLongs(3)
  val as = Array.fill(n.toInt) { readLine.toInt }

  val perSecond = x + y + 2
  val resolution = BigInt(x * y)

  for (a <- as) {
    var remain = a % perSecond
    if (remain == 0) println("Both")
    else {
      var px, py = 0L
      while (remain > 0) {
        val dx = (px + 1) * resolution / x
        val dy = (py + 1) * resolution / y
        if (dx == dy) {
          remain -= 2
          if (remain <= 0) println("Both")
        } else if (dx < dy) {
          remain -= 1
          px += 1
          if (remain <= 0) println("Vanya")
        } else {
          remain -= 1
          py += 1
          if (remain <= 0) println("Vova")
        }
      }
    }
  }
}

import scala.collection._

object D extends App {

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

  val Array(n, x, y) = readLongs(3)
  val as = Array.fill(n.toInt) { readLine.toInt }

  val perSecond = x + y
  val resolution = x * y

  for (a <- as) {
    var remain = a % perSecond
    if (remain == 0) println("Both")
    else {
      var px, py = 0L
      while (remain > 0) {
        val dx = (px + 1) * resolution / x
        val dy = (py + 1) * resolution / y
        if (dx == dy) {
          remain -= 2
          if (remain <= 0) println("Both")
        } else if (dx < dy) {
          remain -= 1
          px += 1
          if (remain <= 0) println("Vanya")
        } else {
          remain -= 1
          py += 1
          if (remain <= 0) println("Vova")
        }
      }
    }
  }
}

import scala.collection._

object D extends App {

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

  val Array(n, x, y) = readLongs(3)
  val as = Array.fill(n.toInt) { readLine.toInt }

  val perSecond = x + y + 2
  val resolution = x * y

  for (a <- as) {
    var remain = a % perSecond
    if (remain == 0) println("Both")
    else {
      var px, py = 0L
      while (remain > 0) {
        val dx = (px + 1) * resolution / x
        val dy = (py + 1) * resolution / y
        if (dx == dy) {
          remain -= 2
          if (remain <= 0) println("Both")
        } else if (dx < dy) {
          remain -= 1
          px += 1
          if (remain <= 0) println("Vanya")
        } else {
          remain -= 1
          py += 1
          if (remain <= 0) println("Vova")
        }
      }
    }
  }
}

import java.util.Scanner

object D extends App {
  def cnt(t: Long) = t / x + t / y - t / (x * y)

  def bs(s: Long) = {
    var l = s * x * y / (x + y)
    var r = (s + 2) * x * y / (x + y)

    while (r - l > 1) {
      val p = (l + r) / 2
      cnt(p) match {
        case c if c < s => l = p + 1
        case c if c > s => r = p - 1
        case _ => r = p
      }
    }

    if (cnt(l) == s) l else r
  } ensuring {
    r => {
      val c = cnt(r)
      s <= c && c <= s + 1
    }
  }

  val sc = new Scanner(System.in)

  val n = sc.nextInt()
  val x = sc.nextLong()
  val y = sc.nextLong()

  for (i <- 1 to n) {
    val s = sc.nextLong()

    val t = bs(s)

    Console.println {
      (t % x == 0, t % y == 0) match {
        case (true, true) => "Both"
        case (true, false) => "Vova"
        case (false, true) => "Vanya"
        case _ => throw new RuntimeException(t.toString)
      }
    }
  }
}

import java.util.Scanner

object D extends App {
  def cnt(t: Long) = t * x / (x * y) + t * y / (x * y)
  val sc = new Scanner(System.in)

  val n = sc.nextInt()
  val x = sc.nextLong()
  val y = sc.nextLong()

  for (i <- 1 to n) {
    val s = sc.nextLong()

    var t = s * x * y / (x + y)
    while (cnt(t) < s) t += 1

    Console.println {
      (t % x == 0, t % y == 0) match {
        case (true, true) => "Both"
        case (true, false) => "Vanya"
        case (false, true) => "Vasya"
        case _ => throw new RuntimeException(t.toString)
      }
    }
  }
}


T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15.  Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.

The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.

Print q numbers, i-th number must be the answer to the i-th query.

import io.StdIn.readLine

object D extends App {
  val Array(n, q) = readLine().split("\\s+").map(_.toLong)

  val root = State(Nil, (n + 1) / 2, (n + 1) / 4)

  case class State(path: List[State], k: Long, step: Long) {
    def command(c: Char) = c match {
      case 'L' ⇒ if (step == 0L) this else State(this :: path, k - step, step / 2)
      case 'R' ⇒ if (step == 0L) this else State(this :: path, k + step, step / 2)
      case 'U' ⇒ path match {
        case prev :: rest ⇒ prev
        case Nil ⇒ this
      }
    }
  }

  def find(k: Long, node: State = root): State =
    if (node.k == k) node
    else if (node.k < k) find(k, node.command('R'))
    else find(k, node.command('L'))

  for (_ ← 1 to q.toInt) {
    val u = readLine().toLong
    val path = readLine()
    println(path.foldLeft(find(u)) {_ command _}.k)
  }
}