The project of a data center of a Big Software Company consists of n computers connected by m cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is not yet approved, it wasn't determined yet in which direction information will go along each cable. The cables are put so that each computer is connected with each one, perhaps through some other computers.The person in charge of the cleaning the data center will be Claudia Ivanova, the janitor. She loves to tie cables into bundles using cable ties. For some reasons, she groups the cables sticking out of a computer into groups of two, and if it isn't possible, then she gets furious and attacks the computer with the water from the bucket.It should also be noted that due to the specific physical characteristics of the Very Important Information, it is strictly forbidden to connect in one bundle two cables where information flows in different directions.The management of the data center wants to determine how to send information along each cable so that Claudia Ivanova is able to group all the cables coming out of each computer into groups of two, observing the condition above. Since it may not be possible with the existing connections plan, you are allowed to add the minimum possible number of cables to the scheme, and then you need to determine the direction of the information flow for each cable (yes, sometimes data centers are designed based on the janitors' convenience...)

The first line contains two numbers, n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of computers and the number of the already present cables, respectively. Each of the next lines contains two numbers ai, bi (1 ≤ ai, bi ≤ n) — the indices of the computers connected by the i-th cable. The data centers often have a very complex structure, so a pair of computers may have more than one pair of cables between them and some cables may connect a computer with itself.

In the first line print a single number p (p ≥ m) — the minimum number of cables in the final scheme. In each of the next p lines print a pair of numbers ci, di (1 ≤ ci, di ≤ n), describing another cable. Such entry means that information will go along a certain cable in direction from ci to di. Among the cables you printed there should be all the cables presented in the original plan in some of two possible directions. It is guaranteed that there is a solution where p doesn't exceed 500 000. If there are several posible solutions with minimum possible value of p, print any of them.

NotePicture for the first sample test. The tied pairs of cables are shown going out from the same point.  Picture for the second test from the statement. The added cables are drawin in bold.  Alternative answer for the second sample test:

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(val from: Int, val to: Int, val id: Int) {
  }

  var graph: Array[List[GraphEdge]] = null
  var graphPos: Array[Iterator[GraphEdge]] = null
  var visit: Array[Boolean] = null
  var outputEdgeId: Int = 0

  def dfs(node: Int): Unit = {
    while (graphPos(node).hasNext) {
      val next = graphPos(node).next()
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        if ((outputEdgeId & 1) == 1) {
          out.println(node + 1 + " " + (next.to + 1))
        } else {
          out.println(next.to + 1 + " " + (node + 1))
        }
        outputEdgeId += 1
      }
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[List[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = Nil
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) = new GraphEdge(u, v, i) :: graph(u)
      graph(v) = new GraphEdge(v, u, i) :: graph(v)
    }
    val oddNode = {
      for (i <- 0 until n if (graph(i).size & 1) == 1) yield i
    }
    var edgeId = m
    for (i <- 0 until(oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i + 1), edgeId) :: graph(oddNode(i))
        graph(oddNode(i + 1)) = new GraphEdge(oddNode(i + 1), oddNode(i), edgeId) :: graph(oddNode(i + 1))
      } else {
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))
      }
      edgeId += 1
    }
    if ((edgeId & 1) != 0) {
      graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)
      graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)
      edgeId += 1
    }
    graphPos = new Array[Iterator[GraphEdge]](n)
    for (i <- 0 until n) {
      graphPos(i) = graph(i).iterator
    }
    visit = new Array[Boolean](edgeId)
    out.println(edgeId)
    dfs(0)
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

import java.io._
import java.util.StringTokenizer
import collection.mutable.ArrayBuffer

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {
    val from = fromNode
    val to = toNode
    val id = edgeId
  }

  var graph: Array[ArrayBuffer[GraphEdge]] = null
  var paths: ArrayBuffer[GraphEdge] = null
  var visit: Array[Boolean] = null

  def dfs(node: Int): Unit = {
    for (next <- graph(node)) {
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        paths += next
      }
    }
  }

  def solve(): Unit = {
    val a = new GraphEdge(1, 1,1 )
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayBuffer[GraphEdge]()
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) += new GraphEdge(u, v, i)
      graph(v) += new GraphEdge(v, u, i)
    }
    val oddNode = for (i <- 0 until n if ((graph(i).size & 1) == 1)) yield i
    var edgeId = m
    for (i <- 0 until (oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)
        graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)
      } else {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
      }
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    paths = new ArrayBuffer[GraphEdge]
    dfs(0)
    out.println(edgeId)
    for (edge <- paths.reverse) {
      out.println((edge.from + 1) + " " + (edge.to + 1))
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(val from: Int, val to: Int, val id: Int) {
  }

  var graph: Array[List[GraphEdge]] = null
  var graphPos: Array[Int] = null
  var visit: Array[Boolean] = null
  var outputEdgeId: Int = 0

  def dfs(node: Int): Unit = {
    while (graphPos(node) < graph(node).length) {
      val next = graph(node)(graphPos(node))
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        if ((outputEdgeId & 1) == 1) {
          println(node + 1 + " " + (next.to + 1))
        } else {
          println(next.to + 1 + " " + (node + 1))
        }
      }
      graphPos(node) += 1
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[List[GraphEdge]](n)
    graphPos = new Array[Int](n)
    for (i <- 0 until n) {
      graph(i) = Nil
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) = new GraphEdge(u, v, i) :: graph(u)
      graph(v) = new GraphEdge(v, u, i) :: graph(v)
    }
    val oddNode = {
      for (i <- 0 until n if (graph(i).size & 1) == 1) yield i
    }
    var edgeId = m
    for (i <- 0 until(oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i + 1), edgeId) :: graph(oddNode(i))
        graph(oddNode(i + 1)) = new GraphEdge(oddNode(i + 1), oddNode(i), edgeId) :: graph(oddNode(i + 1))
      } else {
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))
      }
      edgeId += 1
    }
    if ((edgeId & 1) != 0) {
      graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)
      graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    out.println(edgeId)
    dfs(0)
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

import java.io._
import java.util.StringTokenizer
import collection.mutable.ArrayBuffer

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {
    val from = fromNode
    val to = toNode
    val id = edgeId
  }

  var graph: Array[ArrayBuffer[GraphEdge]] = null
  var paths: ArrayBuffer[GraphEdge] = null
  var visit: Array[Boolean] = null

  def dfs(node: Int): Unit = {
    for (next <- graph(node)) {
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        paths += next
      }
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    println(n, m)
    graph = new Array[ArrayBuffer[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayBuffer[GraphEdge]()
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) += new GraphEdge(u, v, i)
      graph(v) += new GraphEdge(v, u, i)
    }
    val oddNode = for (i <- 0 until n if ((graph(i).size & 1) == 1)) yield i
    var edgeId = m
    for (i <- 0 until (oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)
        graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)
      } else {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
      }
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    paths = new ArrayBuffer[GraphEdge]
    dfs(0)
    out.println(edgeId)
    for (edge <- paths.reverse) {
      out.println((edge.from + 1) + " " + (edge.to + 1))
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(val from: Int, val to: Int, val id: Int) {
  }

  var graph: Array[List[GraphEdge]] = null
  var graphPos: Array[Int] = null
  var visit: Array[Boolean] = null
  var outputEdgeId: Int = 0

  def dfs(node: Int): Unit = {
    while (graphPos(node) < graph(node).length) {
      val next = graph(node)(graphPos(node))
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        if ((outputEdgeId & 1) == 1) {
          println(node + 1 + " " + (next.to + 1))
        } else {
          println(next.to + 1 + " " + (node + 1))
        }
        outputEdgeId += 1
      }

      graphPos(node) += 1
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[List[GraphEdge]](n)
    graphPos = new Array[Int](n)
    for (i <- 0 until n) {
      graph(i) = Nil
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) = new GraphEdge(u, v, i) :: graph(u)
      graph(v) = new GraphEdge(v, u, i) :: graph(v)
    }
    val oddNode = {
      for (i <- 0 until n if (graph(i).size & 1) == 1) yield i
    }
    var edgeId = m
    for (i <- 0 until(oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i + 1), edgeId) :: graph(oddNode(i))
        graph(oddNode(i + 1)) = new GraphEdge(oddNode(i + 1), oddNode(i), edgeId) :: graph(oddNode(i + 1))
      } else {
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))
        graph(oddNode(i)) = new GraphEdge(oddNode(i), oddNode(i), edgeId) :: graph(oddNode(i))
      }
      edgeId += 1
    }
    if ((edgeId & 1) != 0) {
      graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)
      graph(0) = new GraphEdge(0, 0, edgeId) :: graph(0)
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    out.println(edgeId)
    dfs(0)
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

import java.io._
import java.util.StringTokenizer
import collection.mutable.ArrayBuffer

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {
    val from = fromNode
    val to = toNode
    val id = edgeId
  }

  var graph: Array[ArrayBuffer[GraphEdge]] = null
  var paths: ArrayBuffer[GraphEdge] = null
  var visit: Array[Boolean] = null

  def dfs(node: Int): Unit = {
    for (next <- graph(node)) {
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        paths += next
      }
    }
  }

  def solve(): Unit = {
    val a = new GraphEdge(1, 1,1 )
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayBuffer[GraphEdge]()
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) += new GraphEdge(u, v, i)
      graph(v) += new GraphEdge(v, u, i)
    }
    val oddNode = for (i <- 0 until n if ((graph(i).size & 1) == 1)) yield i
    var edgeId = m
    for (i <- 0 until (oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)
        graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)
      } else {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
      }
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    paths = new ArrayBuffer[GraphEdge]
    dfs(0)
    out.println(edgeId)
    for (edge <- paths.reverse) {
      out.println(edge.from + 1 + " " + (edge.to + 1))
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

import java.io._
import java.util.StringTokenizer
import collection.mutable.ArrayBuffer

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {
    val from = fromNode
    val to = toNode
    val id = edgeId
  }

  var graph: Array[ArrayBuffer[GraphEdge]] = null
  var paths: ArrayBuffer[GraphEdge] = null
  var visit: Array[Boolean] = null

  def dfs(node: Int): Unit = {
    for (next <- graph(node)) {
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        paths += next
        println(next.from + " " + next.to)
      }
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayBuffer[GraphEdge]()
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) += new GraphEdge(u, v, i)
      graph(v) += new GraphEdge(v, u, i)
    }
    val oddNode = {
      for (i <- 0 until n if (graph(i).size & 1) == 1) yield i
    }
    var edgeId = m
    for (i <- 0 until (oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)
        graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)
      } else {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
      }
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    paths = new ArrayBuffer[GraphEdge]
    dfs(0)
    out.println(edgeId)
    for (edge <- paths.reverse) {
      out.println((edge.from + 1) + " " + (edge.to + 1))
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

import java.io._
import java.util.StringTokenizer
import collection.mutable.ArrayBuffer

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {
    val from = fromNode
    val to = toNode
    val id = edgeId
  }

  var graph: Array[ArrayBuffer[GraphEdge]] = null
  var paths: ArrayBuffer[GraphEdge] = null
  var visit: Array[Boolean] = null

  def dfs(node: Int): Unit = {
    for (next <- graph(node)) {
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        paths += next
      }
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayBuffer[GraphEdge]()
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) += new GraphEdge(u, v, i)
      graph(v) += new GraphEdge(v, u, i)
    }
    val oddNode = {
      for (i <- 0 until n if (graph(i).size & 1) == 1) yield i
    }
    var edgeId = m
    for (i <- 0 until(oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)
        graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)
      } else {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
      }
      edgeId += 1
    }
    if ((edgeId & 1) != 0) {
      graph(0) += new GraphEdge(0, 0, edgeId)
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    paths = new ArrayBuffer[GraphEdge]
    dfs(0)
    out.println(edgeId)
    for (i <- (0 until edgeId).reverse) {
      val edge = paths(i)
      if ((i & 1) == 0) {
        out.println((edge.from + 1) + " " + (edge.to + 1))
      } else {
        out.println((edge.to + 1) + " " + (edge.from + 1))
      }
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

import java.io._
import java.util.StringTokenizer
import collection.mutable.ArrayBuffer

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  class GraphEdge(fromNode: Int, toNode: Int, edgeId: Int) {
    val from = fromNode
    val to = toNode
    val id = edgeId
  }

  var graph: Array[ArrayBuffer[GraphEdge]] = null
  var paths: ArrayBuffer[GraphEdge] = null
  var visit: Array[Boolean] = null

  def dfs(node: Int): Unit = {
    for (next <- graph(node)) {
      if (!visit(next.id)) {
        visit(next.id) = true
        dfs(next.to)
        paths += next
      }
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[GraphEdge]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayBuffer[GraphEdge]()
    }
    for (i <- 0 until m) {
      var (u, v) = (nextInt, nextInt)
      u -= 1
      v -= 1
      graph(u) += new GraphEdge(u, v, i)
      graph(v) += new GraphEdge(v, u, i)
    }
    val oddNode = {
      for (i <- 0 until n if (graph(i).size & 1) == 1) yield i
    }
    var edgeId = m
    for (i <- 0 until(oddNode.size, 2)) {
      if (i + 1 < oddNode.size) {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i + 1), edgeId)
        graph(oddNode(i + 1)) :+ new GraphEdge(oddNode(i + 1), oddNode(i), edgeId)
      } else {
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
        graph(oddNode(i)) += new GraphEdge(oddNode(i), oddNode(i), edgeId)
      }
      edgeId += 1
    }
    if ((edgeId & 1) != 0) {
      graph(0) += new GraphEdge(0, 0, edgeId)
      edgeId += 1
    }
    visit = new Array[Boolean](edgeId)
    paths = new ArrayBuffer[GraphEdge]
    dfs(0)
    out.println(edgeId)
    for (i <- (1 until edgeId).reverse) {
      val edge = paths(i)
      if ((i & 1) == 0) {
        out.println((edge.from + 1) + " " + (edge.to + 1))
      } else {
        out.println((edge.to + 1) + " " + (edge.from + 1))
      }
    }
  }

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


The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.

The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa ≠ xb, ya ≠ yb). The second line contains integer n — the number of radiators (1 ≤ n ≤ 103). Then n lines contain the heaters' coordinates as "xi yi ri", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≤ ri ≤ 1000. Several radiators can be located at the same point.

Print the only number — the number of blankets you should bring.

NoteIn the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5).In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.

import collection.JavaConversions._

object P144B extends App {
    val Array(xa,ya,xb,yb) = readLine.split(" ").map(_.toInt)
    val coordinates = ((for (x <- math.min(xa,xb) to math.max(xa,xb); y <- List(ya,yb)) yield (x,y)) ++
    	(for (y <- math.min(ya,yb) to math.max(ya,yb); x <- List(xa,xb)) yield (x,y)))
    val generals = new java.util.LinkedList[(Int,Int)]()
    for(e <- coordinates) generals.add(e)
    val n = readLine.toInt
    for (i <- 1 to n){
      val Array(x,y,r) = readLine.split(" ").map(_.toInt)
      val iter = generals.iterator()
      while(iter.hasNext()){
        val e = iter.next()
        if(math.sqrt( math.pow(x-e._1,2) + math.pow(y-e._2,2) ) <= r) iter.remove()
      }
    }
    print(generals.toSet.size)
}


Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:   the government chooses some subset of people (maybe all of them);  the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain the test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$) — the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.

NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{1}{3}]$$$.

object B extends App {
  case class Savings(x: Int, as: List[Int])

  val t = scala.io.StdIn.readInt()

  private def wealthy(s: Savings): Int = {
    val Savings(x, as) = s

    val (ps, rs) = as.sorted.span(_ < x)
    val rl = rs.length

    val overage: Long = rs.foldLeft(0L)(_ + _ - x)

    val pl = ps.reverse
      .foldLeft((overage, 0)) {
        case ((overage, count), a) =>
          if (overage < x - a) (overage, count)
          else (overage - x + a, count + 1)
      }
      ._2

    rl + pl
  }

  val input = (0 until t)
    .foldLeft(List.empty[Savings]) { (acc, _) =>
      val Array(n, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Savings(x, as) :: acc
    }
    .reverse

  val output = input.map(wealthy)

  println(output.mkString("\n"))
}

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 totalCases = in.nextInt()
    (1 to totalCases).foreach{ _ =>
      val n = in.nextInt()
      val x = in.nextLong()
      val a = (1 to n).map(_ => in.nextLong()).sorted.reverse.toArray
      var ans = 0
      var cumSum = 0L
      a.indices.foreach{ i =>
        val newSum = cumSum + a(i)
        if(newSum >= x*(i+1)){
          ans = i+1
        }
        cumSum = newSum
      }
      out.println(ans)

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

object B extends App {
  case class Savings(x: Int, as: List[Int])

  val t = scala.io.StdIn.readInt()

  private def wealthy(s: Savings): Int = {
    val Savings(x, as) = s

    val (ps, rs) = as.sorted.span(_ <= x)
    val rl = rs.length

    val overage = rs.foldLeft(0L)(_ + _ - x)

    val pl = ps
      .foldLeft(List.empty[Int]) {
        case (acc, a) =>
          val deficit = acc.foldLeft((x - a).toLong)(_ + x - _)

          if (overage - deficit >= 0) a :: acc
          else acc

      }
      .length

    rl + pl
  }

  val input = (0 until t)
    .foldLeft(List.empty[Savings]) { (acc, _) =>
      val Array(n, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Savings(x, as) :: acc
    }
    .reverse

  val output = input.map(wealthy)

  println(output.mkString("\n"))
}


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.

Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.

NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.

object GrowTree extends App {
    val (n, boards) = readFromTerminal()
    println(compute(n, boards))

    def readFromTerminal() = {
        val n = readInt()
        val boards = readLine().split(' ').map(x => x.toInt).toList
//        val boards = List.range(1, n)
        (n, boards)
    }

    def compute(n: Int, boards: List[Int]): BigInt = {
        if (n == 0)
            return 0
        if (n == 1)
            return Math.pow(boards.head, 2).toInt
        val sortedBoards = boards.sorted
        var boundary = n/2
        val lowNumber = BigInt.int2bigInt(sortedBoards.take(boundary).sum)
        val highNumber = BigInt.int2bigInt(sortedBoards.takeRight(n - boundary).sum)
        (lowNumber * lowNumber) + (highNumber * highNumber)
    }
}

object GrowTree extends App {
    val (n, boards) = readFromTerminal()
    println(compute(n, boards))

    def readFromTerminal() = {
        val n = readInt()
        val boards = readLine().split(' ').map(x => x.toInt).toList
        (n, boards)
    }

    def compute(n: Int, boards: List[Int]): Int = {
        if (n == 0)
            return 0
        if (n == 1)
            return boards(0)
        val sortedBoards = boards.sorted
        var boundary = n/2
//        println(sortedBoards.take(boundary).sum)
//        println(sortedBoards.takeRight(n - boundary).sum)
        (Math.pow(sortedBoards.take(boundary).sum,2.0) + Math.pow(sortedBoards.takeRight(n-boundary).sum, 2.0)).intValue()
    }
}

object GrowTree extends App {
    val (n, boards) = readFromTerminal()
    println(compute(n, boards))

    def readFromTerminal() = {
        val n = readInt()
        val boards = readLine().split(' ').map(x => x.toInt).toList
        (n, boards)
    }

    def compute(n: Int, boards: List[Int]): Int = {
        if (n == 0)
            return 0
        if (n == 1)
            return Math.pow(boards(0), 2).toInt
        val sortedBoards = boards.sorted
        var boundary = n/2
//        println(sortedBoards.take(boundary).sum)
//        println(sortedBoards.takeRight(n - boundary).sum)
        (Math.pow(sortedBoards.take(boundary).sum,2.0) + Math.pow(sortedBoards.takeRight(n-boundary).sum, 2.0)).intValue()
    }
}


There are $$$n$$$ points on a plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$. You have two horizontal platforms, both of length $$$k$$$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $$$y$$$-coordinate) and have integer borders. If the left border of the platform is $$$(x, y)$$$ then the right border is $$$(x + k, y)$$$ and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $$$y$$$-coordinate.When you place both platforms on a plane, all points start falling down decreasing their $$$y$$$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer $$$t$$$ independent test cases.For better understanding, please read the Note section below to see a picture for the first test case.

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 two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the number of points and the length of each platform, respectively. The second line of the test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is $$$x$$$-coordinate of the $$$i$$$-th point. The third line of the input contains $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$), where $$$y_i$$$ is $$$y$$$-coordinate of the $$$i$$$-th point. All points are distinct (there is no pair $$$1 \le i < j \le n$$$ such that $$$x_i = x_j$$$ and $$$y_i = y_j$$$). 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: the maximum number of points you can save if you place both platforms optimally.

NoteThe picture corresponding to the first test case of the example:Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points $$$(1, -1)$$$ and $$$(2, -1)$$$ and the second one between points $$$(4, 3)$$$ and $$$(5, 3)$$$. Vectors represent how the points will fall down. As you can see, the only point we can't save is the point $$$(3, 7)$$$ so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point $$$(5, 3)$$$ doesn't fall at all because it is already on the platform.

//package codeforces.contests._1409

object TwoPlatforms {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)

      val arr = io.StdIn.readLine.split(" ").map(_.toInt).sorted

      io.StdIn.readLine.split(" ").map(_.toInt) // dirty read

      val right: IndexedSeq[Int] = {
        val right = new Array[Int](n)

        @scala.annotation.tailrec
        def loopR(i: Int = 0, j: Int = 0): Unit = {
          if (i != n) {
            if (j == n || arr(i) + k < arr(j)) {
              right(i) = j - i
              loopR(i + 1, j max (i + 1))
            }
            else loopR(i, j + 1)
          }
        }

        loopR()
        right
      }

      val rightMax = right.scanRight(Int.MinValue)(_ max _)

      val left: IndexedSeq[Int] = {
        val left = new Array[Int](n)

        @scala.annotation.tailrec
        def loopL(i: Int = n - 1, j: Int = n - 1): Unit = {
          if (i >= 0) {
            if (j < 0 || arr(i) - k > arr(j)) {
              left(i) = i - j
              loopL(i - 1, j min (i - 1))
            }
            else loopL(i, j - 1)
          }
        }

        loopL()
        left
      }

      val leftMax = left.scanLeft(Int.MinValue)(_ max _).tail

      @scala.annotation.tailrec
      def loop(i: Int = 0, acc: Int = Int.MinValue): Int = {
        if (i == n) acc
        else {
          loop(
            i + 1,
            acc max {
              right(i) + {
                val rightResult = if (i + right(i) + 1 < n) rightMax(i + right(i) + 1) else Int.MinValue
                val leftResult = if (i > 0) leftMax(i - 1) else Int.MinValue
                val result = leftResult max rightResult

                if (result == Int.MinValue) 0 else result
              }
            }
          )
        }
      }

      println {
        loop()
      }
    }
  }
}


You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.The forestThe Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):  MovesBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:   Do nothing.  Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.  If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement. After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).Mikemon battleIf you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).Your goalYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.Goal of other breedersBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.Your taskPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.

The first line consists of two integers: r and c (1 ≤ r, c ≤ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell:    'T': A cell occupied by a tree.  'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map.  'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map.  A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).  It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.

A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.

NoteThe following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:  The three breeders on the left side of the map will be able to battle you — the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.For the second example, you should post this sequence in your Blog:  Here's what happens. First, you move one cell to the right.  Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.  You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.  Finally, you make another move by leaving the forest.

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val s = Array.ofDim[String](r)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    s(i) = readString
    for (j <- 0 until c) {
      val ch = s(i)(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)
  dists(exit._1)(exit._2) = 0

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit; ch = s(i)(j); if (ch > '0' && ch <= '9')) sum += (ch - '0')

  println(sum)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      val ch = s(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch >= '0' && ch <= '9') breeders(i)(j) = ch - '0'
        else if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)
  val djs = Array(0, 0, -1, 1)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (isFree.isDefinedAt(ni)) {
        val nj = j + djs(m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill[Byte](r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      val ch = s(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch >= '0' && ch <= '9') breeders(i)(j) = (ch - '0').toByte
        else if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val s = Array.ofDim[String](r)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    s(i) = readString
    for (j <- 0 until c) {
      val ch = s(i)(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)
  dists(exit._1)(exit._2) = 0

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit; if (s(i)(j) > '0' && s(i)(j) <= '9')) sum += (s(i)(j) - '0')

  println(sum)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      val ch = s(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch >= '0' && ch <= '9') breeders(i)(j) = ch - '0'
        else if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      if (s(j) != 'T') isFree(i) += j
      if (s(j) >= '0' && s(j) <= '9') breeders(i)(j) = s(j) - '0'
      else if (s(j) == 'S') start = (i, j)
      else if (s(j) == 'E') exit = (i, j)
    }
  }
  if (r == 1000) println("read")
  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)
  val djs = Array(0, 0, -1, 1)
  if (r == 1000) println("init")

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + djs(m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }
  if (r == 1000) println("shortest")

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    isFree(i) ++= s.indices.filter(s(_) != 'T')
    s.indices.withFilter(j => s(j) >= '0' && s(j) <= '9').foreach(j => breeders(i)(j) = s(j) - '0')
    var sj = s.indexOf('S')
    if (sj >= 0) start = (i, sj)
    val ej = s.indexOf('E')
    if (ej >= 0) exit = (i, ej)
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(0)

  val moves = Array((-1, 0), (1, 0), (0, -1), (0, 1))

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    for ((di, dj) <- moves; ni = i + di; nj = j + dj; if isFree.isDefinedAt(ni) && isFree(ni)(nj)) {
      toVisit += ((ni, nj))
      isFree(ni)(nj) = false
      dists(ni)(nj) = dists(i)(j) + 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}


You are given two integers $$$b$$$ and $$$w$$$. You have a chessboard of size $$$10^9 \times 10^9$$$ with the top left cell at $$$(1; 1)$$$, the cell $$$(1; 1)$$$ is painted white.Your task is to find a connected component on this chessboard that contains exactly $$$b$$$ black cells and exactly $$$w$$$ white cells. Two cells are called connected if they share a side (i.e. for the cell $$$(x, y)$$$ there are at most four connected cells: $$$(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)$$$). A set of cells is called a connected component if for every pair of cells $$$C_1$$$ and $$$C_2$$$ from this set, there exists a sequence of cells $$$c_1$$$, $$$c_2$$$, ..., $$$c_k$$$ such that $$$c_1 = C_1$$$, $$$c_k = C_2$$$, all $$$c_i$$$ from $$$1$$$ to $$$k$$$ are belong to this set of cells and for every $$$i \in [1, k - 1]$$$, cells $$$c_i$$$ and $$$c_{i + 1}$$$ are connected.Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and any suitable connected component.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains two integers $$$b$$$ and $$$w$$$ ($$$1 \le b, w \le 10^5$$$) — the number of black cells required and the number of white cells required. It is guaranteed that the sum of numbers of cells does not exceed $$$2 \cdot 10^5$$$ ($$$\sum w + \sum b \le 2 \cdot 10^5$$$).

For each query, print the answer to it. If it is impossible to find the required component, print "NO" on the first line. Otherwise, print "YES" on the first line. In the next $$$b + w$$$ lines print coordinates of cells of your component in any order. There should be exactly $$$b$$$ black cells and $$$w$$$ white cells in your answer. The printed component should be connected. If there are several answers, you can print any. All coordinates in the answer should be in the range $$$[1; 10^9]$$$.

object Main {
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import java.io._

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val no = "NO"
  val yes = "YES"

  def main (args: Array[String]){

    val q = in.next().toInt
    for (_ <- 1 to q) {
      val b, w = in.next().toInt
      // a <= c
      val a = Math.min(b, w)
      val c = Math.max(b, w)

      if (a*2 + (a-1) + 2 < c) {
        pw.println(no)
      }
      else {

        var ans: List[(Int, Int)] = Nil

        // whiteを全部入れる
        for (i <- 1 to a) {
          ans = (2, i*2) :: ans
        }

        var black: List[(Int, Int)] = Nil

        //
        for (i <- 1 to a) {
          black = (1, i*2) :: (3, i*2) :: black
        }

        // 経路を作る()
        for (i <- 0 to a) {
          black = (2, i*2+1) :: black
        }

        ans = ans ++ black.take(c)

        // blackがminだったら右にずらす
        if (b < w)
          ans = ans.map {case (x, y) => (x+1, y)}

        pw.println(yes)
        ans.foreach{ case (x, y) => pw.println(s"$x $y") }
      }
    }

    pw.flush()
  }
}

import java.io._
class InputReader(stream: InputStream) {
  import java.util.StringTokenizer

  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

object Main {
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import java.io._

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val no = "NO"
  val yes = "YES"

  def main (args: Array[String]){

    val q = in.next().toInt
    for (_ <- 1 to q) {
      val b, w = in.next().toInt
      // a <= c
      val a = Math.min(b, w)
      val c = Math.max(b, w)

      if (a*2 + (a-1) + 2 < b) {
        pw.println(no)
      }
      else {

        var ans: List[(Int, Int)] = Nil

        // whiteを全部入れる
        for (i <- 1 to a) {
          ans = (2, i*2) :: ans
        }

        var black: List[(Int, Int)] = Nil

        //
        for (i <- 1 to a) {
          black = (1, i*2) :: (3, i*2) :: black
        }

        // 経路を作る()
        for (i <- 0 to a) {
          black = (2, i*2+1) :: black
        }

        ans = ans ++ black.take(c)

        // blackがminだったら右にずらす
        if (b < w)
          ans = ans.map {case (x, y) => (x+1, y)}

        pw.println(yes)
        ans.foreach{ case (x, y) => pw.println(s"$x $y") }
      }
    }

    pw.flush()
  }
}

import java.io._
class InputReader(stream: InputStream) {
  import java.util.StringTokenizer

  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:  Swap i-th and j-th rows of the matrix;  Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.

The first line contains an integer n (2 ≤ n ≤ 1000) — the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 ≤ xk, yk ≤ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct.

Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m ≤ 105) — the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 ≤ t ≤ 2, 1 ≤ i, j ≤ n, i ≠ j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.

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

object test6 extends App {
    val n=readInt
    val mat=Array.ofDim[Int](n+1,n+1)
    val rows=new Array[Int](n+1)
    val cols=new Array[Int](n+1)

    for(_<-1 until n){
        val Array(x,y)=readLine.split(" ").map(_.toInt)
        mat(x)(y)=1
        rows(x)+=1
        cols(y)+=1
    }

    val swapRows=(i:Int, j:Int)=>{
        val tmp=mat(i)
        mat(i)=mat(j)
        mat(j)=tmp

        val tt=rows(i)
        rows(i)=rows(j)
        rows(j)=tt
    }

    val swapCols=(i:Int, j:Int)=>{
        for(k<-1 to n){
            val tmp=mat(k)(i)
            mat(k)(i)=mat(k)(j)
            mat(k)(j)=tmp
        }
        val tmp=cols(i)
        cols(i)=cols(j)
        cols(j)=tmp
    }

    var ab=collection.mutable.ArrayBuffer[String]()
    for(i<-n to 1 by -1){
        var col=i
        while(col>0 && cols(col)>0) col-=1
        if(col>0 && col!=i){
            swapCols(i,col)
            ab+="2 %d %d".format(col, i)
        }

        var row=i
        while(row>0 && rows(row)==0) row-=1
        if(row>0 && row!=i){
            swapRows(i,row)
            ab+="1 %d %d".format(row,i)
        }

        for(j<-1 to i) if(mat(i)(j)==1) cols(j)-=1
    }
    println(ab.size)
    println(ab.mkString("\n"))
}

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

object test6 extends App {
    val n=readInt
    val mat=Array.ofDim[Int](n+1,n+1)
    val rows=new Array[Int](n+1)
    val cols=new Array[Int](n+1)

    for(_<-1 until n){
        val Array(x,y)=readLine.split(" ").map(_.toInt)
        mat(x)(y)=1
        rows(x)+=1
        cols(y)+=1
    }

    val swapRows=(i:Int, j:Int)=>{
        val tmp=mat(i)
        mat(i)=mat(j)
        mat(j)=tmp

        val tt=rows(i)
        rows(i)=rows(j)
        rows(j)=tt
    }

    val swapCols=(i:Int, j:Int)=>{
        for(k<-1 to n){
            val tmp=mat(k)(i)
            mat(k)(i)=mat(k)(j)
            mat(k)(j)=tmp
        }
        val tmp=cols(i)
        cols(i)=cols(j)
        cols(j)=tmp
    }

    var ab=collection.mutable.ArrayBuffer[String]()
    for(i<-n to 1 by -1){
        var col=i
        while(col>0 && cols(col)>0) col-=1
        if(col>0 && col!=i){
            swapCols(i,col)
            ab+="2 %d %d".format(col, i)
        }

        var row=i
        while(row>0 && rows(row)==0) row-=1
        if(row>0 && row!=i){
            swapRows(i,row)
            ab+="1 %d %d".format(row,i)
        }

        for(j<-1 to i) if(mat(i)(j)==1) cols(j)-=1
    }
    println(ab.size)
    ab.foreach(println)
}


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

object P4C {
    def main(args : Array[String]) {
        val n = readLine.toInt
        val d = collection.mutable.Map[String, Int]()
        for (_ <- 1 to n) {
            val s = readLine
            d get s match {
                case Some(x) => {println(s + x); d(s) = x + 1}
                case None => {println("OK"); d(s) = 1}
            }
        }
    }
}

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

/**
  * Created by nhan on 5/30/16.
  */

object Registrator {

  def main(args: Array[String]) {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(System.out)
    val dict = collection.mutable.HashMap.empty[String, Int]
    val numLine = br.readLine().toInt
    (1 to numLine).foreach { _ =>
        val line = br.readLine()
        if (dict contains line) {
          val value = dict(line) + 1
          dict.update(line, value)
          out.println(line + value)
        } else {
          dict.update(line, 0)
          out.println("OK")
        }
    }
    out.close
  }
}

import scala.collection.mutable._

object Main {
    def main(args : Array[String]) {
        val n = Integer valueOf(readLine())
        val db = new HashMap[String, Int]

        for(i <- 0 until n) {
            val name = readLine()
            if(!(db contains name)) {
                db += name -> 1
            } else {
                db += name -> (db(name) + 1)
            }

            if(db(name) == 1) {
                println("OK");
            } else {
                println(name + (db(name) - 1))
            }
        }
    }
}

import scala.collection.mutable._

object Main {
    def main(args : Array[String]) {
        val n = Integer valueOf(readLine())
        val db = new HashMap[String, Int]

        for(i <- 0 until n) {
            val name = readLine()

            db get name match {
                case Some(k) => {
                    println(name + k);
                    db += name -> (k + 1)
                }

                case None => {
                    println("OK")
                    db += name -> 1
                }
            }
        }
    }
}

import java.util.Scanner

object CRegSystem extends App {

  val scanner = new Scanner(System.in)
  val num = scanner.nextInt()

  val m = scala.collection.mutable.HashMap.empty[String, Int]

  val queries = ((0 until num) map (it => scanner.next())).toList

  queries.foreach {
    item =>
      m.get(item) match {
        case Some(v) =>
          m.put(item, v + 1)
          println("" + item + v)
        case None =>
          m.put(item, 1)
          println("OK")
      }
  }

}

import scala.collection.mutable

object C4 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val map = mutable.Map.empty[String, Int].withDefaultValue(0)
    for (i <- 0 until n) {
      val name = scala.io.StdIn.readLine
      if(map.contains(name)) {
        println(s"${name}${map(name)}")
        map(name) += 1
      } else {
        map(name) = 1
        println("OK")
      }
    }
  }
}

import scala.io.StdIn

object A extends App {

  var map: Map[String, Int] = Map()

  val n = StdIn.readInt()
  (1 to n).foreach { _ =>
    val s = StdIn.readLine()
    if(map.contains(s)) {
      map = map + (s -> (map(s) + 1))
      println(s + map(s))
    } else {
      map = map + (s -> 0)
      println("OK")
    }
  }
}

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

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

  val N = sc.nextInt
  sc.nextLine
  type DB = mutable.Map[String, Int]
  val db: DB = mutable.Map.empty[String, Int]
  for (_ <- 0 until N) {
    val request = sc.nextLine
    if (db.contains(request)) {
      val i = db(request) + 1
      db += (request -> i)
      out.println(request + i.toString)
    }
    else {
      db += (request -> 0)
      out.println("OK")
    }
  }
  out.close
}

import java.io.PrintWriter
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.BufferedReader
import java.util

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object C4 extends App {

  val reader = new BufferedReader(new InputStreamReader(System.in))
  var writer = new BufferedWriter(new PrintWriter(System.out))
  val n: Int = reader.readLine().toInt
  val db: mutable.HashMap[String, Int] = mutable.HashMap.empty[String, Int]
  val answer: util.ArrayList[String] = new util.ArrayList[String](n)
  for (i <- 0 until n) {
    val input = reader.readLine()
    if (!db.contains(input)) {
      writer.write("OK\n")
      db += (input -> 1)
    } else {
      var i1: Int = db.get(input).get
      var found = false
      while (!found) {
        if (!db.contains(input + i1)) {
          found = true
        } else {
          i1 += 1
        }
      }
      val s: String = input + i1 + "\n"
      writer.write(s)
      db += (input -> (i1 + 1))
      db += (input + i1 -> 1)
    }
  }

  writer.close()
  reader.close()
}

object Cf4C extends App {
  val d =collection.mutable.Map[String, Int]()
  for(_ <-1 to readInt()){
    val s = readLine
    d get s match {
      case Some(x) => {println(s+x);d(s)=x+1}
      case None => {println("OK");d(s)=1}
    }
  }
}

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

object C {

  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 Long.parseLong(next)
  }

  def solve = {
    val n = nextInt
    val names = new util.HashSet[String]()
    val namedInd = new util.HashMap[String, Int]()
    for (i <- 0 until n) {
      val name = next
      if (names.contains(name)) {
        val ind = namedInd.get(name)
        out.println(name + ind.toString)
        names.add(name + ind.toString)
        namedInd.remove(name)
        namedInd.put(name, ind + 1)
      } else {
        names.add(name)
        namedInd.put(name, 1)
        out.println("OK")
      }
    }
  }

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

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val map = scala.collection.mutable.Map[String, Int]()
    for (_ <- 1 to n) {
      val name = readLine()
      map.get(name) match {
        case None =>
          map(name) = 1
          println("OK")
        case Some(i) =>
          map(name) = i + 1
          println(name + i)
      }
    }
  }
}

import scala.collection.mutable.Map
object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val map = Map[String, Int]()
    for (i <- 1 to n) {
      val str = readLine()
      if (map.contains(str)) {
        map(str) += 1
        println(str + map(str).toString)
      }
      else {
        map += (str -> 0)
        println("OK")
      }
    }
  }
}

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

object _4_C extends App {
  val n = readInt()
  val counter = new mutable.HashMap[String, Int]

  for (_ <- 1 to n) {
    val name = readLine()
    var c = counter.getOrElseUpdate(name, 0)
    if (c == 0) {
      println("OK")
    }
    else {
      println(s"$name$c")
    }
    c += 1
    counter(name) = c
  }
}

import scala.collection.mutable.HashMap

object RegistrationSystem{
    class Name(var nameString : String = "",var count : Int = 0,var printedCount : Int = 0)
    def main(args : Array[String]){

        var n : Int = readLine.toInt
        var namesMap : HashMap[String,Name] =  new HashMap[String,Name]()
        var namesArray : Array[String] = new Array[String](n)
        for(i <- 0 to n-1){
            var name : String = readLine
            namesArray(i) = name
            if (namesMap.contains(name)){
                namesMap(name).count += 1
            }
            else{
                namesMap.put(name,new Name(name,1,0))
            }
        }
        for(name <- namesArray){
            if (namesMap(name).printedCount == 0){
                println("OK")
            }
            else{
                println(name + namesMap(name).printedCount)
            }
            namesMap(name).printedCount += 1
        }
    }
}

object P4C {
    def main(args : Array[String]) {
        val n = readLine.toInt
        val d = collection.mutable.Map[String, Int]()
        for (_ <- 1 to n) {
            val s = readLine
            if (d contains s) {
                val ds = d(s)
                println(s + ds)
                d(s) = ds + 1
            } else {
                println("OK")
                d(s) = 1
            }
        }
    }
}

import java.util

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object C4 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val db: mutable.HashSet[String] = mutable.HashSet.empty[String]
  val answer: util.ArrayList[String] = new util.ArrayList[String](n)
  for (i <- 0 until n) {
    val input = scala.io.StdIn.readLine()
    if (!db.contains(input)) {
      answer.add("OK")
      db += input
    } else {
      var found = false
      var i: Int = 1
      while (!found) {
        if (!db.contains(input + i)) {
          found = true
        } else {
          i += 1
        }
      }
      answer .add (input + i)
      db += (input + 1)
    }
  }

  println(answer.toArray.mkString("\n"))
}


Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.

The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle.

In a single line print a single integer — the answer to the problem.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Int](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) += 1
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((count, 0), diff)) => sum + count
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, n), false)) if n == 1 => sum + 1
    case(sum, ((count, _), _)) => sum
  })
}

object A extends App {

  def solve(n: Int, as: Array[Int], bs: Array[Int]): Int = {

     n - as.indices.count(i => bs.indices.exists(j => as(i) == bs(j) && i != j))
  }

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

  val n = readString.toInt
  val as = Array.ofDim[Int](n)
  val bs = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    val Array(a, b) = readInts
    as(i) = a
    bs(i) = b
  }

  println(solve(n, as, bs))
}

// package R187d2

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

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

  val N = sc.nextInt
  val xs = Array.fill(N, 2)(sc.nextInt)

  def isUnableToOpen(i: Int): Boolean = {
    @tailrec
    def loop(j :Int): Boolean =
      if (j == N) true
      else if (i == j) loop(j + 1)
      else if (xs(i)(0) == xs(j)(1)) false
      else loop(j + 1)

    loop(0)
  }

  out.println(List.range(0, N).count(isUnableToOpen))
  out.close
}

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

  val n = readInt()

  val (as, bs) = (0 until n).foldLeft((List.empty[Int], List.empty[Int])) {
    case ((as, bs), _) =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      (a :: as, b :: bs)
  }

  val ans = n - (as zip bs).collect {
    case (a, b) if a == b && bs.count(_ == a) > 1 => 1
    case (a, b) if a != b && bs.exists(_ == a)    => 1
  }.sum

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield { readLine().split(" ").map(_.toInt) }
    val Array(as, bs) = a.transpose.toArray
    val r = for {
      (x, i) <- as.zipWithIndex
      (y, j) <- bs.zipWithIndex
      if i != j
      if x == y
    } yield(i)
    println(n - r.toSet.size)
  }
}

object Second{
  def readString() : String = {
    var yo = scala.io.StdIn.readLine()
    yo
  }
  def readInt() : Int = {
    var yo = scala.io.StdIn.readInt();
    yo
  }
 def solve(n : Int , as : Array[Int] , bs : Array[Int]) : Int = {
   val ho = n - as.indices.count(i => bs.indices.exists(j => as(i) == bs(j) && i != j))
   ho
 }
   def main(args : Array[String]){
    var n = readInt()
    var as = Array.ofDim[Int](n)
    var bs = Array.ofDim[Int](n)
    for(i <- 0 until n){
      var Array(a, b ) = readString().split(" ").map(_.toInt)
      as(i) = a
      bs(i) = b
    }
    print(solve(n , as , bs))
   }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((_, false), diff)) => sum
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + 1
    case(sum, ((count, _), _)) => sum + count
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((count, false), diff)) => sum + count
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + 1
    case(sum, ((count, _), _)) => sum
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((_, false), diff)) => sum
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + count
    case(sum, ((count, _), _)) => sum + count - 1
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((count, false), diff)) => sum + count
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + count - 1
    case(sum, ((count, _), _)) => sum
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((_, false), diff)) => sum
    case(sum, ((count, _), false)) => sum + count
    case(sum, ((count, _), _)) => sum + count - 1
  })
}

object A extends App {

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

  def solve(n: Int): Int = {

  	if (n < 0) {
  	  val p = -n
  	  -math.min(p / 10, (p / 100) * 10 + p % 10)
  	} else n
  }

  val n = readString.toInt

  println(solve(n))
}

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

  val n       = readInt()
  val bottles = Array.fill(1001)(0)
  val same    = Array.fill(1001)(false)
  val opened  = Array.fill(1001)(false)

  (0 until n).foreach { _ =>
    val Array(bottle, other) = readLine().split(" ").map(_.toInt)

    bottles(bottle) += 1

    if (bottle == other) same(bottle) = true
    else opened(other) = true
  }

  same.zipWithIndex.foreach {
    case (false, _)  => ()
    case (_, bottle) => opened(bottle) = opened(bottle) || bottles(bottle) > 1
  }

  val ans = bottles.zipWithIndex.foldLeft(n) {
    case (closed, (0, _)) => closed
    case (closed, (count, bottle)) =>
      closed - (if (opened(bottle)) count else 0)
  }

  println(ans)
}

object ASerejaAndBottles extends App {
  import scala.io.StdIn._
  import scala.collection.mutable

  val n = readInt()

  val bottles      = Array.fill(1001)(0)
  val descriptions = Array.fill(1001)(List.empty[Int])

  (0 until n).foreach { _ =>
    val Array(bottle, description) = readLine().split(" ").map(_.toInt)
    bottles(bottle) += 1
    descriptions(bottle) ::= description
  }

  val ans = bottles.zipWithIndex.foldLeft(n) {
    case (closed, (_, 0)) => closed
    case (closed, (count, bottle)) =>
      descriptions(bottle).exists { opener =>
        if (opener == bottle) count > 1
        else bottles(opener) > 0
      } match {
        case true => closed - count
        case _    => closed
      }
  }

  println(ans)
}

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

  val n = readInt()

  val (as, bs) = (0 until n).foldLeft((List.empty[Int], List.empty[Int])) {
    case ((as, bs), _) =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      (a :: as, b :: bs)
  }

  val ans = n - (as zip bs).collect {
    case (a, b) if a != b && bs.exists(_ == a) => 1
  }.sum

  println(ans)
}

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

  val n = readInt()
  val ans = (0 until n).foldLeft(0) {
    case (acc, _) =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      acc + (if (a == b) 1 else 0)
  }

  println(ans)
}

object ASerejaAndBottles extends App {
  import scala.io.StdIn._
  import scala.collection.mutable

  val n = readInt()

  val bottles      = Array.fill(1001)(0)
  val opened       = Array.fill(1001)(false)

  (0 until n).foreach { _ =>
    val Array(bottle, other) = readLine().split(" ").map(_.toInt)

    bottles(bottle) += 1

    opened(other) = opened(other) ||
      (if (bottle == other) bottles(bottle) > 1 else true)
  }

  val ans = bottles.zipWithIndex.foldLeft(n) {
    case (closed, (0, _)) => closed
    case (closed, (count, bottle)) =>
      closed - (if (opened(bottle)) count else 0)
  }

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield {readLine().split(" ").map(_.toInt) }
    val f = a.filter(t => t(0) != t(1))
    if (f.size == 0) println(n)
    else {
      val Array(as, bs) = f.transpose.map(_.toSet).toArray
      val r = as -- bs
      println(n - f.size + r.size)
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield {readLine().split(" ").map(_.toInt) }
    val f = a.filter(t => t(0) != t(1))
    if (f.size == 0) println(n)
    else {
      val Array(as, bs) = f.transpose.toArray
      val bss = bs.toSet
      val r = as filter (e => ! (bss contains e))
      println(n - f.size + r.size)
    }
  }
}


Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.

For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.

NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.

import scala.io.StdIn

object Main {

  def solveTest(tc: Int): Unit = {
    val s = StdIn.readLine()
    val a = s.map(c => c.toInt - 'a'.toInt + 1).toList
    val n = s.length
    val alice = if (n % 2 == 0) a.sum else Math.max(a.sum - a.head, a.sum - a(n - 1))
    val bob = a.sum - alice
    if (alice > bob) {
      println(s"Alice ${alice - bob}")
    } else {
      println(s"Bob ${bob - alice}")
    }
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (tc <- 1 to t) {
      solveTest(tc)
    }
  }
}


Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.

In a single line print the answer to the problem — the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.

NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object C extends App {

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

  val n = readInt
  val ss = Array.fill(n) { readLine }

  val sb = new StringBuilder

  for (pos <- ss.head.indices) {
    var ch = '.'
    var i = 0
    while (i < n && (ch == '.' || ch == ss(i)(pos) || ss(i)(pos) == '?')) {
      if (ss(i)(pos) != '?') {
        ch = ss(i)(pos)
      }
      i += 1
    }
    if (i == n) sb += (if (ch == '.') 'x' else ch)
    else sb += '?'
  }

  println(sb.toString)
}