You are given a directed graph with $$$n$$$ vertices and $$$m$$$ directed edges without self-loops or multiple edges.Let's denote the $$$k$$$-coloring of a digraph as following: you color each edge in one of $$$k$$$ colors. The $$$k$$$-coloring is good if and only if there no cycle formed by edges of same color.Find a good $$$k$$$-coloring of given digraph with minimum possible $$$k$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 5000$$$, $$$1 \le m \le 5000$$$) — the number of vertices and edges in the digraph, respectively. Next $$$m$$$ lines contain description of edges — one per line. Each edge is a pair of integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — there is directed edge from $$$u$$$ to $$$v$$$ in the graph. It is guaranteed that each ordered pair $$$(u, v)$$$ appears in the list of edges at most once.

In the first line print single integer $$$k$$$ — the number of used colors in a good $$$k$$$-coloring of given graph. In the second line print $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is a color of the $$$i$$$-th edge (in order as they are given in the input). If there are multiple answers print any of them (you still have to minimize $$$k$$$).

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

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

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

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

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

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

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, M = ni()
    val (from, to) = na2(M, -1)
    val g = packDGraph(N, from, to)
    if (topologicalSort(g) != null) {
      out.println(1)
      val ans = map(M){_ => 1 }
      out.println(ans.mkString(" "))
    } else {
      out.println(2)
      val ans = Array.ofDim[Int](M)
      REP(M) { i =>
        ans(i) = if (from(i) < to(i)) 1 else 2
      }
      out.println(ans.mkString(" "))
    }
  }

  def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP_r(m) { i => // 順序維持する
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
    }
    t
  }
  /**
    * @return 閉路の場合はnull
    */
  def topologicalSort(g: Array[Array[Int]]): Array[Int] = {
    val n = g.length
    val L = Array.ofDim[Int](n)
    var ptr = 0
    val S = Array.ofDim[Int](n)
    var last, cur = 0
    val deg = Array.ofDim[Int](n)
    REP(n) { i =>
      REP(g(i).length) { j =>
        deg(g(i)(j)) += 1
      }
    }

    REP(n) { i =>
      if (deg(i) == 0) {
        S(last) = i
        last += 1
      }
    }

    while(cur < last) {
      val v = S(cur)
      cur += 1
      L(ptr) = v
      ptr += 1

      REP(g(v).length) { i =>
        val u = g(v)(i)
        deg(u) -= 1
        if (deg(u) == 0) {
          S(last) = u
          last += 1
        }
      }
    }

    // 閉路チェック
    REP(n) { i =>
      if (deg(i) > 0) return null
    }
    L
  }
}

import scala.collection.mutable

object D {

  def main(args: Array[String]): Unit = {}
  val out = new java.io.PrintWriter(System.out)
  val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
  def tokenizeLine = new java.util.StringTokenizer(in.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

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

  val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val res = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    res(i) = if (u > v) 2 else 1
    precedingBuilders(v - 1) += u - 1
  }

  val preceding = precedingBuilders.map(_.result)

  var hasCycle = false
  val color = Array.fill(n)(0)

  def dfs0(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceding(u).length) {
      val v = preceding(u)(i)
      if (color(v) == 0) dfs0(v)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i)

  if (hasCycle) {
    out.println(2)
    out.println(res.mkString(" "))
  } else {
    out.println(1)
    out.println(Array.fill(m)(1).mkString(" "))
  }

  out.flush()
}

import scala.collection.mutable

object D {

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

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

  val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val res = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    res(i) = if (u > v) 2 else 1
    precedingBuilders(v - 1) += u - 1
  }

  val preceding = precedingBuilders.map(_.result)

  var hasCycle = false
  val color = Array.fill(n)(0)

  def dfs0(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceding(u).length) {
      val v = preceding(u)(i)
      if (color(v) == 0) dfs0(v)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i)

  if (hasCycle) {
    System.out.println(2)
    System.out.println(res.mkString(" "))
  } else {
    System.out.println(1)
    System.out.println(Array.fill(m)(1).mkString(" "))
  }
}

import scala.collection.mutable

object D {

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

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

  val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val res = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    res(i) = if (u > v) 2 else 1
    precedingBuilders(v - 1) += u - 1
  }

  val preceding = precedingBuilders.map(_.result)

  var hasCycle = false
  val color = Array.fill(n)(0)

  def dfs0(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceding(u).length) {
      val v = preceding(u)(i)
      if (color(v) == 0) dfs0(v)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i)

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D {

  def main(args: Array[String]): Unit = {}
  val out = new java.io.PrintWriter(System.out)
  val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
  def tokenizeLine = new java.util.StringTokenizer(in.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

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

  val precedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val res = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(u, v) = readInts(2)
    res(i) = if (u > v) 2 else 1
    precedingBuilders(v - 1) += u - 1
  }

  val preceding = precedingBuilders.map(_.result)

  var hasCycle = false
  val color = Array.fill(n)(0)

  def dfs0(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceding(u).length) {
      val v = preceding(u)(i)
      if (color(v) == 0) dfs0(v)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i)

  if (hasCycle) {
    System.out.println(2)
    System.out.println(res.mkString(" "))
  } else {
    System.out.println(1)
    System.out.println(Array.fill(m)(1).mkString(" "))
  }
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    if (edge >= 0) sortedBuilder += edge
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  val sorted = sortedBuilder.result

//println(sorted.mkString(" "))
  for (i <- sorted.indices) res(sorted(i)) = 1 + i % 2

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(n)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, 0, step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

//  val sorted = sortedBuilder.result
//
//  val order = Array.ofDim[Int](n)
//  for (i <- sorted.indices) {
//    order(sorted(i)) = 1 + i % 2
//  }

  //println(sorted.map(_ + 1).mkString(" "))
  //println(order.mkString(" "))
  //for (i <- 0 until m) res(i) = order(edgeTo(i))

  val visited = Array.fill(n)(false)

  def dfs1(u: Int, u0: Int, step: Int): Unit = {
    /*if (step > 0 && u == u0) hasCycle = true
    else */if (!visited(u)) {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val edge = adjs(u)(i)
        if (!visited(edgeTo(edge))) {
          res(edge) = step % 2 + 1
          dfs1(edgeTo(edge), u0, step + 1)
        }
        i += 1
      }
    }
  }
//
//  var iter = 0
  for (u <- 0 until n) {
    if (!visited(u)) {
      dfs1(u, u, 0)
    }
  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    //if (edge >= 0) sortedBuilder += edge
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  //val sorted = sortedBuilder.result

//println(sorted.mkString(" "))
  //for (i <- sorted.indices) res(sorted(i)) = 1 + i % 2

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  val sorted = sortedBuilder.result

  val order = Array.ofDim[Int](n)
  for (i <- sorted.indices) {
    order(sorted(i)) = 1 + i % 2
  }

  //println(sorted.mkString(" "))
  //println(order.mkString(" "))
  for (i <- 0 until m) res(i) = order(edgeTo(i))

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  val sorted = sortedBuilder.result

  val order = Array.ofDim[Int](n)
  for (i <- sorted.indices) {
    order(sorted(i)) = 1 + i % 2
  }

  println(sorted.mkString(" "))
  println(order.mkString(" "))
  for (i <- 0 until m) res(i) = order(edgeTo(i))

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)

  var hasCycle = false
  val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)

  def dfs1(u: Int, u0: Int, step: Int): Unit = {
    if (step > 0 && u == u0) hasCycle = true
    else if (iters(u) == 0) {
      iters(u) = iter
      var i = 0
      while (i < adjs(u).length) {
        val edge = adjs(u)(i)
        color(edge) = step % 2 + 1
        dfs1(edgeTo(edge), u0, step + 1)
        i += 1
      }
    }
  }

  var iter = 0
  for (u <- 0 until n) {
    if (iters(u) == 0) {
      iter += 1
      dfs1(u, u, 0)
    }
  }

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

  if (hasCycle) {
    println(2)
    println(color.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  val sorted = sortedBuilder.result

//println(sorted.mkString(" "))
  val order = Array.ofDim[Int](n)
  for (i <- sorted.indices) {
    order(sorted(i)) = 1 + i % 2
  }

  for (i <- 0 until m) res(i) = order(edgeTo(i))

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)

  def dfs0(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      if (color(v) == 0) dfs0(v)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i)

  val res = Array.fill(m)(0)

  def dfs1(u: Int, u0: Int, step: Int): Unit = {
    /*if (step > 0 && u == u0) hasCycle = true
    else */if (iters(u) == 0) {
      iters(u) = iter
      var i = 0
      while (i < adjs(u).length) {
        val edge = adjs(u)(i)
        res(edge) = step % 2 + 1
        dfs1(edgeTo(edge), u0, step + 1)
        i += 1
      }
    }
  }

  var iter = 0
  for (u <- 0 until n) {
    if (iters(u) == 0) {
      iter += 1
      dfs1(u, u, 0)
    }
  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(n)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  val sorted = sortedBuilder.result

  val order = Array.ofDim[Int](n)
  for (i <- sorted.indices) {
    order(sorted(i)) = 1 + i % 2
  }

  //println(sorted.mkString(" "))
  //println(order.mkString(" "))
  for (i <- 0 until m) res(i) = order(edgeTo(i))

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  val iters = Array.fill(n)(0)
  val color = Array.fill(m)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  def dfs0(u: Int, edge: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      if (color(v) == 0) dfs0(v, adjs(u)(i))
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    if (edge >= 0) sortedBuilder += edge
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

  val sorted = sortedBuilder.result

  val res = Array.fill(m)(1)
//println(sorted.mkString(" "))
  for (i <- sorted.indices) res(sorted(i)) = 1 + i % 2

  //
//  def dfs1(u: Int, u0: Int, step: Int): Unit = {
//    /*if (step > 0 && u == u0) hasCycle = true
//    else */if (iters(u) == 0) {
//      iters(u) = iter
//      var i = 0
//      while (i < adjs(u).length) {
//        val edge = adjs(u)(i)
//        res(edge) = step % 2 + 1
//        dfs1(edgeTo(edge), u0, step + 1)
//        i += 1
//      }
//    }
//  }
//
//  var iter = 0
//  for (u <- 0 until n) {
//    if (iters(u) == 0) {
//      iter += 1
//      dfs1(u, u, 0)
//    }
//  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(n)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, 0, step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

//  val sorted = sortedBuilder.result
//
//  val order = Array.ofDim[Int](n)
//  for (i <- sorted.indices) {
//    order(sorted(i)) = 1 + i % 2
//  }

  //println(sorted.map(_ + 1).mkString(" "))
  //println(order.mkString(" "))
  //for (i <- 0 until m) res(i) = order(edgeTo(i))

  val visited = Array.fill(n)(false)

  def dfs1(u: Int, u0: Int, step: Int): Unit = {
    /*if (step > 0 && u == u0) hasCycle = true
    else */if (!visited(u)) {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val edge = adjs(u)(i)
        res(edge) = step % 2 + 1
        dfs1(edgeTo(edge), u0, step + 1)
        i += 1
      }
    }
  }
//
//  var iter = 0
  for (u <- 0 until n) {
    if (!visited(u)) {
      dfs1(u, u, 0)
    }
  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object D extends App {

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

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

  val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val preceedingBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
  val edgeTo = Array.ofDim[Int](m)

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

  val adjs = adjBuilders.map(_.result)
  val preceeding = preceedingBuilders.map(_.result)

  var hasCycle = false
  //val iters = Array.fill(n)(0)
  val color = Array.fill(n)(0)
  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val res = Array.fill(m)(1)

  def dfs0(u: Int, edge: Int, step: Int = 0): Unit = {
    color(u) = 1
    var i = 0
    while (i < preceeding(u).length) {
      val v = preceeding(u)(i)
      //res(adjs(u)(i)) = 1 + step % 2
      if (color(v) == 0) dfs0(v, adjs(u)(i), step + 1)
      else if (color(v) == 1) hasCycle = true
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs0(i, -1)

//  val sorted = sortedBuilder.result
//
//  val order = Array.ofDim[Int](n)
//  for (i <- sorted.indices) {
//    order(sorted(i)) = 1 + i % 2
//  }

  //println(sorted.map(_ + 1).mkString(" "))
  //println(order.mkString(" "))
  //for (i <- 0 until m) res(i) = order(edgeTo(i))

  val visited = Array.fill(n)(false)

  def dfs1(u: Int, u0: Int, step: Int): Unit = {
    /*if (step > 0 && u == u0) hasCycle = true
    else */if (!visited(u)) {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val edge = adjs(u)(i)
        res(edge) = step % 2 + 1
        dfs1(edgeTo(edge), u0, step + 1)
        i += 1
      }
    }
  }
//
//  var iter = 0
  for (u <- 0 until n) {
    if (!visited(u)) {
      dfs1(u, u, 0)
    }
  }

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

  if (hasCycle) {
    println(2)
    println(res.mkString(" "))
  } else {
    println(1)
    println(Array.fill(m)(1).mkString(" "))
  }

  Console.flush
}


Roy and Biv have a set of n points on the infinite number line.Each point has one of 3 colors: red, green, or blue.Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).Help them compute the minimum cost way to choose edges to satisfy the above constraints.

The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points. The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.

Print a single integer, the minimum cost way to solve the problem.

NoteIn the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.

object F extends App {

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

  val Array(n) = readInts(1)
  val ps = Array.ofDim[Long](n)
  val cs = Array.ofDim[Char](n)

  for (i <- 0 until n) {
    val Array(p, c) = readLine.split(" ")
    ps(i) = p.toLong
    cs(i) = c.head
  }

  var prevG = -1L
  var firstR, firstB, lastR, lastB = -1L

  var i = 0
  while (i < n && prevG < 0) {
    val pos = ps(i)
    cs(i) match {

      case 'R' =>
        if (firstR < 0) firstR = pos
        lastR = pos

      case 'B' =>
        if (firstB < 0) firstB = pos
        lastB = pos

      case 'G' =>
        prevG = pos
    }
    i += 1
  }

  var sum = 0L

  if (prevG >= 0) {
    if (firstR >= 0) sum += prevG - firstR
    if (firstB >= 0) sum += prevG - firstB
  } else {
    if (firstR >= 0) sum += lastR - firstR
    if (firstB >= 0) sum += lastB - firstB
  }

  var prevB, prevR = prevG
  var maxGapR, maxGapB = 0L

  while (i < n) {
    val pos = ps(i)
    cs(i) match {

      case 'R' =>
        val gapR = pos - prevR
        if (gapR > maxGapR) maxGapR = gapR
        prevR = pos

      case 'B' =>
        val gapB = pos - prevB
        if (gapB > maxGapB) maxGapB = gapB
        prevB = pos

      case 'G' =>

        val gapR = pos - prevR
        if (gapR > maxGapR) maxGapR = gapR

        val gapB = pos - prevB
        if (gapB > maxGapB) maxGapB = gapB

        val gapG = pos - prevG
        val sum1 = 2 * gapG
        val sum2 = 3 * gapG - maxGapR - maxGapB
        sum += Math.min(sum1, sum2)

        maxGapB = 0
        maxGapR = 0
        prevR = pos
        prevB = pos
        prevG = pos
    }

    i += 1
  }

  sum += prevR - prevG
  sum += prevB - prevG

  println(sum)
}

object F extends App {

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

  val Array(n) = readInts(1)
  val ps = Array.ofDim[Long](n)
  val cs = Array.ofDim[Char](n)

  for (i <- 0 until n) {
    val Array(p, c) = readLine.split(" ")
    ps(i) = p.toLong
    cs(i) = c.head
  }

  var prevG = -1L
  var firstR, firstB = -1L

  var i = 0
  while (i < n && prevG < 0) {
    val pos = ps(i)
    cs(i) match {

      case 'R' =>
        if (firstR < 0) firstR = pos

      case 'B' =>
        if (firstB < 0) firstB = pos

      case 'G' =>
        prevG = pos
    }
    i += 1
  }

  var sum = 0L
  if (firstR >= 0) sum += prevG - firstR
  if (firstB >= 0) sum += prevG - firstB

  var prevB, prevR = prevG
  var maxGapR, maxGapB = 0L

  while (i < n) {
    val pos = ps(i)
    cs(i) match {

      case 'R' =>
        val gapR = pos - prevR
        if (gapR > maxGapR) maxGapR = gapR
        prevR = pos

      case 'B' =>
        val gapB = pos - prevB
        if (gapB > maxGapB) maxGapB = gapB
        prevB = pos

      case 'G' =>

        val gapR = pos - prevR
        if (gapR > maxGapR) maxGapR = gapR

        val gapB = pos - prevB
        if (gapB > maxGapB) maxGapB = gapB

        val gapG = pos - prevG
        val sum1 = 2 * gapG
        val sum2 = 3 * gapG - maxGapR - maxGapB
        sum += Math.min(sum1, sum2)

        maxGapB = 0
        maxGapR = 0
        prevR = pos
        prevB = pos
        prevG = pos
    }

    i += 1
  }

  sum += prevR - prevG
  sum += prevB - prevG

  println(sum)
}


Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes.

Output one integer — the maximal possible distance between time periods.

NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0.

import java.util.Scanner

import scala.collection.mutable

object B extends App {

  val sc = new Scanner(System.in)
  type Segment = (Int, Int)

  val n = sc.nextInt()
  val checkmates = getSegments(n)
  val m = sc.nextInt()
  val programming = getSegments(m)

  val checkmatesL = checkmates.maxBy(_._1)._1
  val checkmatesR = checkmates.minBy(_._2)._2
  val programmingL = programming.maxBy(_._1)._1
  val programmingR = programming.minBy(_._2)._2

  val ans = math.max(programmingL - checkmatesR, checkmatesL - programmingR)
  println(math.max(0, ans))

  def getSegments(n: Int): Set[Segment] = {
    var checkmates = mutable.HashSet[Segment]()
    (1 to n) foreach { _ =>
      val x: Segment = (sc.next().toInt, sc.next().toInt)
      checkmates += x
    }
    checkmates.toSet
  }
}

object _785B extends CodeForcesApp {
   import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val chess, programming = read[Seq[(Int, Int)]]
    write(calc(chess, programming) max calc(programming, chess) max 0)
  }

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

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

import scala.io.StdIn

object TaskB {

  def readData(): Seq[(Int, Int)] = {
    val size = StdIn.readInt()
    1 to size map { _ =>
      val tuple = StdIn.readf2("{0} {1}")
      (tuple._1.toString.toInt, tuple._2.toString.toInt)
    }
  }

  def isCrossed(chessTime: (Int, Int), programmingTime: (Int, Int)): Boolean = {
    if (chessTime._1 >= programmingTime._1 && chessTime._1 <= programmingTime._2) {
      return true
    }

    if (chessTime._2 >= programmingTime._1 && chessTime._2 <= programmingTime._2) {
      return true
    }

    false
  }

  def distance(chessTime: (Int, Int), programmingTime: (Int, Int)): Int = {
    if (isCrossed(chessTime, programmingTime)) {
      0
    } else if (chessTime._1 < programmingTime._1) {
      programmingTime._1 - chessTime._2
    } else {
      chessTime._1 - programmingTime._2
    }
  }

  def main(args: Array[String]): Unit = {
    val chessData = readData()
    val programmingData = readData()

    val distances = for {
      x <- List(
        chessData.minBy(_._1),
        chessData.minBy(_._2),
        chessData.maxBy(_._1),
        chessData.maxBy(_._2))
      y <- List(
        programmingData.minBy(_._1),
        programmingData.minBy(_._2),
        programmingData.maxBy(_._1),
        programmingData.maxBy(_._2)
      )
    } yield {
      distance(x, y)
    }

    println(distances.max)
  }

}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemB extends App {
    import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer
  override def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null
    val out = new PrintWriter(System.out)

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

    def nextInt: Int = next.toInt

    val n = nextInt
    var maxMath = 0
    var minMath = Int.MaxValue
    var maxChess = 0
    var minChess = Int.MaxValue

    for (i <- 1 to n) {
      maxMath = math.max(nextInt, maxMath)
      minMath = math.min(nextInt, minMath)
    }

    val m = nextInt
     for (i <- 1 to m) {
      maxChess = math.max(nextInt, maxChess)
      minChess = math.min(nextInt, minChess)
    }

    val res = math.max(maxChess - minMath, maxMath - minChess)
    println(math.max(0, res))

  }
}

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

import scala.language.postfixOps
import scala.math._

object TaskB extends App {
  val ir = new InputReader(System.in)
  def minMax(a: (Int, Int), b: (Int, Int)) = (max(a._1, b._1), min(a._2, b._2))

  val a = 1 to ir.nextInt map { _ => (ir.nextInt, ir.nextInt) } reduce minMax
  val b = 1 to ir.nextInt map { _ => (ir.nextInt, ir.nextInt) } reduce minMax

  println(max(max(a._1 - b._2, b._1 - a._2), 0))
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

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

  def nextInt: Int = nextString.toInt
}

import java.util.Scanner

import scala.collection.mutable

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

object B extends App {

  val sc = new Scanner(System.in)
  type Segment = (Int, Int)

  val n = sc.nextInt()
  val checkmates = getSegments(n)
  val m = sc.nextInt()
  val programming = getSegments(m)

  val checkmatesL = checkmates.maxBy(_._1)._1
  val checkmatesR = checkmates.minBy(_._2)._2
  val programmingL = programming.maxBy(_._1)._1
  val programmingR = programming.minBy(_._2)._2

  if (checkmatesR < programmingL) {
    println(programmingL - checkmatesR)
  } else if (checkmatesL > programmingR) {
    println(checkmatesL - programmingR)
  } else {
    println(0)
  }

  def getSegments(n: Int): Set[Segment] = {
    var checkmates = mutable.HashSet[Segment]()
    (1 to n) foreach { _ =>
      val x: Segment = (sc.next().toInt, sc.next().toInt)
      checkmates += x
    }
    checkmates.toSet
  }
}

import scala.io.StdIn

object TaskB {

  def readData(): Seq[(Int, Int)] = {
    val size = StdIn.readInt()
    1 to size map { _ =>
      val tuple = StdIn.readf2("{0} {1}")
      (tuple._1.toString.toInt, tuple._2.toString.toInt)
    }
  }

  def isCrossed(chessTime: (Int, Int), programmingTime: (Int, Int)): Boolean = {
    if (chessTime._1 >= programmingTime._1 && chessTime._1 <= programmingTime._2) {
      return true
    }

    if (chessTime._2 >= programmingTime._1 && chessTime._2 <= programmingTime._2) {
      return true
    }

    false
  }

  def distance(chessTime: (Int, Int), programmingTime: (Int, Int)): Int = {
    if (isCrossed(chessTime, programmingTime)) {
      0
    } else if (chessTime._1 < programmingTime._1) {
      programmingTime._1 - chessTime._2
    } else {
      chessTime._2 - programmingTime._1
    }
  }

  def main(args: Array[String]): Unit = {
    val chessData = readData()
    val programmingData = readData()
    val tuples = for {x <- chessData; y <- programmingData} yield (x, y)
    println(tuples.map { tuple => distance(tuple._1, tuple._2) }.max)
  }

}

import scala.io.StdIn

object TaskB {

  def readData(): Seq[(Int, Int)] = {
    val size = StdIn.readInt()
    1 to size map { _ =>
      val tuple = StdIn.readf2("{0} {1}")
      (tuple._1.toString.toInt, tuple._2.toString.toInt)
    }
  }

  def isCrossed(chessTime: (Int, Int), programmingTime: (Int, Int)): Boolean = {
    if (chessTime._1 >= programmingTime._1 && chessTime._1 <= programmingTime._2) {
      return true
    }

    if (chessTime._2 >= programmingTime._1 && chessTime._2 <= programmingTime._2) {
      return true
    }

    false
  }

  def distance(chessTime: (Int, Int), programmingTime: (Int, Int)): Int = {
    if (isCrossed(chessTime, programmingTime)) {
      0
    } else if (chessTime._1 < programmingTime._1) {
      programmingTime._1 - chessTime._2
    } else {
      chessTime._2 - programmingTime._1
    }
  }

  def main(args: Array[String]): Unit = {
    val chessData = readData()
    val programmingData = readData()
    val distances = for {x <- chessData; y <- programmingData} yield distance(x, y)
    println(distances.max)
  }

}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemB extends App {
    import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer
  override def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null
    val out = new PrintWriter(System.out)

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

    def nextInt: Int = next.toInt

    val n = nextInt
    var maxMath = 0
    var minMath = Int.MaxValue
    var maxChess = 0
    var minChess = Int.MaxValue

    for (i <- 1 to n) {
      maxMath = math.max(nextInt, maxMath)
      minMath = math.min(nextInt, minMath)
    }

    val m = nextInt
     for (i <- 1 to m) {
      maxChess = math.max(nextInt, maxChess)
      minChess = math.min(nextInt, minChess)
    }

    val res = math.max(maxChess - minMath, maxMath - minMath)
    println(math.max(0, res))

  }
}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemB extends App {
import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

  override def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null
    val out = new PrintWriter(System.out)

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

    def nextInt: Int = next.toInt

    val n = nextInt
    var maxMath, minMath = 0
    var maxChess, minChess = 0

    for (i <- 1 to n) {
      maxMath = math.max(nextInt, maxMath)
      minMath = math.min(nextInt, minMath)
    }

    val m = nextInt
     for (i <- 1 to m) {
      maxChess = math.max(nextInt, maxChess)
      minChess = math.min(nextInt, minChess)
    }

    val res = math.max(maxChess - minMath, maxMath - minMath)
    println(math.max(0, res))

  }
}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemB extends App {
    import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

  override def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null
    val out = new PrintWriter(System.out)

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

    def nextInt: Int = next.toInt

    val n = nextInt

    val timeForChess = (for (i <- 1 to n) yield (nextInt, nextInt)).sortWith((p1, p2) => p1._2 - p2._2 < 0)
    val m = nextInt
    val timeForMath = (for (i <- 1 to m) yield (nextInt, nextInt)).sortWith((p1, p2) => p1._1 - p2._1 > 0)

    println(math.max(0, timeForMath(0)._1 - timeForChess(0)._2))

  }
}

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

import scala.language.postfixOps
import scala.math.max

object TaskB extends App {
  val ir = new InputReader(System.in)

  val r = 1 to ir.nextInt map { _ => ir.nextInt; ir.nextInt } min
  val l = 1 to ir.nextInt map { _ => val l = ir.nextInt; ir.nextInt; l } max

  println(max(l - r, 0))
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

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

  def nextInt: Int = nextString.toInt
}


On a random day, Neko found $$$n$$$ treasure chests and $$$m$$$ keys. The $$$i$$$-th chest has an integer $$$a_i$$$ written on it and the $$$j$$$-th key has an integer $$$b_j$$$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.The $$$j$$$-th key can be used to unlock the $$$i$$$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $$$a_i + b_j \equiv 1 \pmod{2}$$$. One key can be used to open at most one chest, and one chest can be opened at most once.Find the maximum number of chests Neko can open.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$) — the number of chests and the number of keys. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the numbers written on the treasure chests. The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 10^9$$$) — the numbers written on the keys.

Print the maximum number of chests you can open.

NoteIn the first example, one possible way to unlock $$$3$$$ chests is as follows:  Use first key to unlock the fifth chest,  Use third key to unlock the second chest,  Use fourth key to unlock the first chest. In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).In the third example, no key can unlock the given chest.

object a extends App {
  import scala.io.StdIn.readLine
  import scala.math.min

  val _ = readLine
  def getArr: (Array[Int], Array[Int]) = readLine.split(" ").map(_.toInt).partition(_ % 2 == 0)
  val aa = getArr
  val bb = getArr

  val (aOdd, aEven) = (aa._1.length, aa._2.length)
  val (bOdd, bEven) = (bb._1.length, bb._2.length)

  println(min(aOdd, bEven) + min(aEven, bOdd))

}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    val B = na(M)
    val evenA = A.count(_%2 == 0)
    val evenB = B.count(_%2 == 0)
    val ans = min(evenA, M - evenB) + min(N - evenA, evenB)
    out.println(ans)
  }

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

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

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

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

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

  def debugDim(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m.length) { i =>
      debug(m(i))
    }
  }

  def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }

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

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

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

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

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

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

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

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

object Solution {

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

    val in: Iterator[String] = io.Source.stdin.getLines()
    val Array(m,n) = in.next().split(" ").map(_.toInt)
    val first = in.next().split(" ").map(_.toInt)
    val second = in.next().split(" ").map(_.toInt)

    val fe = first.count(_ % 2 == 0)
    val fo = first.count(_% 2 != 0)
    val se  = second.count(_ % 2 == 0)
    val so  = second.count(_ % 2 != 0)

    println(Math.min(fe, so) + Math.min(fo, se))

  }

}


We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $$$a$$$ yuan for $$$b$$$ kilos (You don't need to care about what "yuan" is), the same as $$$a/b$$$ yuan for a kilo.Now imagine you'd like to buy $$$m$$$ kilos of apples. You've asked $$$n$$$ supermarkets and got the prices. Find the minimum cost for those apples.You can assume that there are enough apples in all supermarkets.

The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 5\,000$$$, $$$1 \leq m \leq 100$$$), denoting that there are $$$n$$$ supermarkets and you want to buy $$$m$$$ kilos of apples. The following $$$n$$$ lines describe the information of the supermarkets. Each line contains two positive integers $$$a, b$$$ ($$$1 \leq a, b \leq 100$$$), denoting that in this supermarket, you are supposed to pay $$$a$$$ yuan for $$$b$$$ kilos of apples.

The only line, denoting the minimum cost for $$$m$$$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $$$10^{-6}$$$. Formally, let your answer be $$$x$$$, and the jury's answer be $$$y$$$. Your answer is considered correct if $$$\frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}$$$.

NoteIn the first sample, you are supposed to buy $$$5$$$ kilos of apples in supermarket $$$3$$$. The cost is $$$5/3$$$ yuan.In the second sample, you are supposed to buy $$$1$$$ kilo of apples in supermarket $$$2$$$. The cost is $$$98/99$$$ yuan.

import java.util.Scanner

import scala.language.implicitConversions

object Supermarket {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }
  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val (n, m) = (sc.nextInt(), sc.nextInt())
    val min_ratio = 0.until(n).map(i => sc.nextInt() * 1.0 / sc.nextInt()).min
    print(min_ratio * m);
  }
}

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

/**
  * Created by amir.
  */

object A extends App{

  class RW(val inputFile: String, val outputFile: String) {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var out = new PrintWriter(new OutputStreamWriter(System.out))

    /* val f = new File(inputFile)
    if (f.exists && f.canRead)
    try {
    br = new BufferedReader(new FileReader(f))
    out = new PrintWriter(new FileWriter(outputFile))
    } catch {
    case e: IOException =>
    e.printStackTrace()
    }*/

    private var st: StringTokenizer = _
    var eof = false

    def nextLine: String = {
      var s = ""
      try
        s = br.readLine()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      s
    }

    def next: String = {
      while (st == null || !st.hasMoreTokens)
        try
          st = new StringTokenizer(br.readLine)
        catch {
          case _: IOException =>
            eof = true
            ""
        }
      st.nextToken
    }

    def nextLong: Long = next.toLong

    def nextInt: Int = next.toInt

    def println: Unit = out.println()

    def println(o: Any): Unit = out.println(o)

    def print(o: Any): Unit = out.print(o)

    def close: Unit = {
      try {
        br.close()
      } catch {
        case e: IOException =>
          e.printStackTrace()
      }

      out.close()
    }
  }

  override def main(args: Array[String]) {
    val rw = new RW("input.txt", "output.txt")

    val n = rw.nextInt
    val m = rw.nextInt
    val costs = for (_ <- 1 to n) yield rw.nextInt.toDouble / rw.nextInt
    rw.println(costs.min * m)
    rw.close
  }
}

object A extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val price = (0 until n).foldLeft(Double.MaxValue)((price, _) => {
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toDouble)
    price.min(a / b)
  })
  println(price * m)
}

object CF919A extends App{
  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt
  println((Seq.fill[Double](n)(sc.nextDouble / sc.nextDouble) min) * m)
}


Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are  non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball.

Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.

NoteIn the first sample, color 2 is dominant in three intervals:  An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.  An interval [4, 4] contains one ball, with color 2 again.  An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt - 1)
  val colors = Array.ofDim[Int](n)

  def dom(i: Int) {
    val map = Array.ofDim[Int](n)
    var index = 0
    (i until n).foreach { j =>
      map(line(j)) += 1
      val candidate = map(line(j))
      if (candidate > map(index) || (candidate == map(index) && line(j) < index))
        index = line(j)
      colors(index) += 1
    }
  }

  (0 until n).foreach(i => dom(i))
  println(colors.mkString(" "))
}


There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i < j and pi > pj.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of swap operations applied to the sequence. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109, ai ≠ bi) — the arguments of the swap operation.

Print a single integer — the number of inversions in the resulting sequence.

NoteIn the first sample the sequence is being modified as follows: . It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).

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

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

import scala.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 lowerBound[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 (!(array(mid) < value)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  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
  }

  val N = 210001;
  val bit: Array[Int] = new Array[Int](N)

  def addBit(pos: Int, value: Int): Unit = {
    var i = pos
    while (i < N) {
      bit(i) += value
      i += (i & (i ^ (i - 1)))
    }
  }

  def getBit(pos: Int): Int = {
    var (i, res) = (pos, 0)
    while (i > 0) {
      res += bit(i)
      i -= (i & (i ^ (i - 1)))
    }
    return res
  }

  def getRange(from: Int, to: Int): Int = {
    return getBit(to) - getBit(from - 1)
  }

  def solve(): Unit = {
    val n = nextInt
    val a = Array.ofDim[Int](n)
    val b = Array.ofDim[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
      b(i) = nextInt
    }
    val pos_set: Set[Int] = a.toSet | b.toSet
    val p = pos_set.toArray.sorted
    val v = pos_set.toArray.sorted
    for (i <- 0 until n) {
      val pa = lowerBound(p, a(i))
      val pb = lowerBound(p, b(i))
      val tuple = (v(pa), v(pb)).swap
      v(pa) = tuple._1
      v(pb) = tuple._2
    }
    var res: Long = 0
    for (i <- 0 until p.length) {
      res += math.abs(p(i) - v(i)) - math.abs(i - lowerBound(p, v(i)))
    }
    for (i <- 0 until p.length) {
      val cur_p = lowerBound(p, v(i)) + 1
      res += getRange(cur_p, N - 1)
      addBit(cur_p, 1)
    }
    out.println(res)
  }

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