import scala.collection.immutable.HashMap

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val n = readInt
        val as = (0 until n).map((x) => (readLine, x + 1))
        val (has0, has1, hasl, zo, oz) = as.foldLeft((false, false, false, HashMap[String, Int](), HashMap[String, Int]())){
            case ((h0, h1, hl, zo, oz), (s, i)) => (s(0), s(s.length - 1)) match {
                case ('0', '0') => (true, h1, hl, zo, oz)
                case ('1', '1') => (h0, true, hl, zo, oz)
                case ('1', '0') => if (zo.contains(s.reverse)){
                    (h0, h1, true, zo - s.reverse, oz)
                }
                else {
                     (h0, h1, hl, zo, oz + (s -> i))
                }
                case ('0', '1') => if (oz.contains(s.reverse)){
                    (h0, h1, true, zo, oz - s.reverse)
                } else {
                    (h0, h1, hl, zo + (s -> i), oz)
                }
                case _ => throw new Exception("")
            }
        }
        if (zo.size == 0 && oz.size == 0) {
            if (hasl || ((has0 && !has1) || (!has0 && has1))) {
                println(0)
                println("")
            } else {
                println(-1)
            }
        }
        else {
        val total = zo.size + oz.size
        val (s1, s2) = (total / 2, total - (total / 2))
        val (k, il) = if (zo.size < oz.size) {
            (oz.size - s2, oz.values.take(oz.size - s2))
        } else {
            (zo.size - s2, zo.values.take(zo.size - s2))
        }
        println(k)
        println(il.mkString(" "))
        }
    }
  }

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    val have01, have10 = mutable.Map.empty[String, Int]
    var have00, have11, haveMixed = false
    var i = 1
    while (i <= n) {
      val s = nextLine
      val l = s.length - 1
      if (s(0) == '0' && s(l) == '0') have00 = true
      else if (s(0) == '1' && s(l) == '1') have11 = true
      else {
        haveMixed = true
        val rev = s.reverse
        if (s(0) == '0' && s(l) == '1') {
          if (have10.contains(rev)) have10 -= rev
          else have01 += s -> i
        } else {
          if (have01.contains(rev)) have01 -= rev
          else have10 += s -> i
        }
      }
      i += 1
    }
    if (have00 && have11 && !haveMixed) out.println(-1)
    else {
      val need = Math.abs(have01.size - have10.size) / 2
      out.println(need)
      val res = if (have01.size > have10.size) have01 else have10
      out.println(res.values.toIterator.take(need).mkString(" "))
    }
  }

  out.println()
  out.flush()

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

import scala.collection.immutable.HashMap

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val n = readInt
        val as = (0 until n).map((x) => (readLine, x + 1))
        val (has0, has1, hasl, zo, oz) = as.foldLeft((false, false, false, HashMap[String, Int](), HashMap[String, Int]())){
            case ((h0, h1, hl, zo, oz), (s, i)) => (s(0), s(s.length - 1)) match {
                case ('0', '0') => (true, h1, hl, zo, oz)
                case ('1', '1') => (h0, true, hl, zo, oz)
                case ('1', '0') => if (zo.contains(s.reverse)){
                    (h0, h1, true, zo - s.reverse, oz)
                }
                else {
                     (h0, h1, hl, zo, oz + (s -> i))
                }
                case ('0', '1') => if (oz.contains(s.reverse)){
                    (h0, h1, true, zo, oz - s.reverse)
                } else {
                    (h0, h1, hl, zo + (s -> i), oz)
                }
                case _ => throw new Exception("")
            }
        }
        if (zo.size == 0 && oz.size == 0) {
            if (hasl || ((has0 && !has1) || (!has0 && has1))) {
                println(0)
                println("")
            } else {
                println(-1)
            }
        }
        val total = zo.size + oz.size
        val (s1, s2) = (total / 2, total - (total / 2))
        val (k, il) = if (zo.size < oz.size) {
            (oz.size - s2, oz.values.take(oz.size - s2))
        } else {
            (zo.size - s2, zo.values.take(zo.size - s2))
        }
        println(k)
        println(il.mkString(" "))
    }
  }

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    val have = mutable.Map.empty[String, Int]
    var have00, have11, haveMixed = false
    var i = 1
    while (i <= n) {
      val s = nextLine
      val l = s.length - 1
      if (s(0) == '0' && s(l) == '0') have00 = true
      else if (s(0) == '1' && s(l) == '1') have11 = true
      else {
        haveMixed = true
        val rev = s.reverse
        if (have.contains(rev)) have -= rev
        else have += s -> i
      }
      i += 1
    }
    if (have00 && have11 && !haveMixed) out.println(-1)
    else {
      val need = have.size / 2
      out.println(need)
      out.println(have.values.toIterator.take(need).mkString(" "))
    }
  }

  out.println()
  out.flush()

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


import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        itsUp = current > prev
      } else {
        hasAnswer = hasAnswer && current < prev
      }
      prev = current
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}

//package codeforces.contest1197

object Pillars {

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

    val (maxValue, index) = seqWithIndex.maxBy(_._1)

    val seq = seqWithIndex.map(_._1)

    def loop(top: Int, l: Int, r: Int): Boolean = {
      val lProspect = if (l >= 0) Some(seq(l)) else None
      val rProspect = if (r < n) Some(seq(r)) else None

      (lProspect, rProspect) match {
        case (Some(ll), Some(rr)) if ll < top && rr < top && ll != rr =>
          if (ll > rr) loop(ll, l - 1, r) else loop(rr, l, r + 1)
        case (Some(ll), None) if ll < top =>
          loop(ll, l - 1, n)
        case (None, Some(rr)) if rr < top =>
          loop(rr, -1, r + 1)
        case (None, None) =>
          true
        case _ =>
          false
      }
    }

    println(if (loop(maxValue, index - 1, index + 1)) "YES" else "NO")
  }

}

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 = ni()
    val A = na(N)
    val p = A.indexWhere(_ == N)
    var ok = true
    var i = p - 1
    while(i >= 0) {
      ok &&= A(i + 1) > A(i) // 単調増加
      i -= 1
    }
    i = p + 1
    while(i < N) {
      ok &&= A(i) < A(i - 1) // 単調減少
      i += 1
    }
    if (ok) out.println("YES")
    else out.println("NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        val change = current < prev
        if (change) {
          prev = current
          itsUp = false
        }
      } else {
        hasAnswer = hasAnswer && current <= prev
        prev = current
      }
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        val change = current <= prev
        if (change) {
          prev = current
          itsUp = false
        }
      } else {
        hasAnswer = hasAnswer && current < prev
        prev = current
      }
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        val change = current < prev
        if (change) {
          prev = current
          itsUp = false
        }
      } else {
        hasAnswer = hasAnswer && current < prev
        prev = current
      }
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}


import scala.collection._

object A 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 xs = readLongs(n)
  val (evens, odds) = xs.partition(_ % 2 == 0)

  val evensSum = evens.sum
  val oddsSum = if (odds.size % 2 == 1) odds.sorted.drop(1).sum else odds.sum
  val res = evensSum + oddsSum

  println(res)
}

/**
  * Created by octavian on 31/01/2016.
  */
object Wet {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("./src/wet.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/wet.out")))

    val n = readInt()
    val numbers : Array[Int] = readLine.split(" ").map(_.toInt).sortWith(_ < _)

    var undesired = -1
    if(oddOdds(numbers)) {
      undesired = firstOdd(numbers)
    }

    var sum: BigInt = 0
    for(i <- 0 until numbers.length) {
      if(i != undesired) {
        sum += numbers(i)
      }
    }

    println(sum)
  }

  def oddOdds(numbers: Array[Int]): Boolean = {
    var odds = 0
    for(i <- 0 until numbers.length) {
      if(numbers(i) % 2 == 1) {
        odds += 1
      }
    }
    return(odds % 2 == 1)
  }

  def firstOdd(numbers: Array[Int]): Int = {
    for(i <- 0 until numbers.length) {
      if(numbers(i) % 2 == 1) {
        return i
      }
    }
    return  0
  }

}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    val odd = a.filter((v) => v % 2 == 1)
    val even = a.filter((v) => v % 2 == 0)
    println(even.sum + odd.sum - (if (odd.length % 2 == 1) odd.min else 0))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val (even, odd) = data.partition(_ % 2 == 0)
  println(even.sum + odd.sum - (if (odd.length % 2 == 0) 0 else odd.min))
}

object A621 {
  @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 input = readLongs(n).sortBy(identity)
    if(input.exists(_%2 == 0) || (input.length > 1 && input(0)%2 == 1)) {
      var sum = input.sum
      var i = 0
      while (i < n && sum % 2 != 0) {
        if(input(i)%2 == 1)
          sum -= input(i)
        i += 1
      }
      println(sum)
    } else {
      println("0")
    }
  }
}

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

object Task {

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = Array.fill(n) { in.nextLong() }
        val s = a.sum
        val answer = if (s % 2 == 0) s else s - a.view.filter(_ % 2 == 1).min
        out.println(answer)
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

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

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

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

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

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

// So you like object Task
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

/**
  * Created with IntelliJ IDEA.
  * User: xie
  * Date: 2/6/16
  * Time: 2:03 PM
  */
object Task {

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = Array.fill(n) { in.nextLong() }
        val s = a.sum
        val answer = if (s % 2 == 0) s else s - a.view.filter(_ % 2 == 1).min
        out.println(answer)
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

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

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

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

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

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

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

object Solution {

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

  def main(args: Array[String]) {

    val n = readLine().toInt
    val a = readInts(n)

    var res:Long = 0
    var firstOdd: Long = 0
    a.sorted(Ordering[Int].reverse).foreach { v =>
      if (v % 2 == 0) res += v
      else  {
        if (firstOdd == 0) firstOdd = v
        else {
          res += firstOdd + v
          firstOdd = 0
        }
      }
    }

    println(res)

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

import scala.io.Source

/**
  * Created by yanluchen on 16/3/14.
  */

object A extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val row = in.next().split(" ").map(_.toLong)
  //  val (even,odd) = row.partition(_ % 2==0)
  val odd = row.filter(_ % 2 != 0)
  val ans = row.sum - (if (odd.length % 2 == 0) 0 else odd.min)
  println(ans)
}


import java.util.Scanner
import scala.annotation.tailrec

object Main {
  val L = "<{[("
  val R = ">}])"
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val inStr = scan.nextLine()
    scan.close()

    val res = Process(inStr,0,Nil,0,0)
    if(res<0){
      print("Impossible")
    }else{
      print(res)
    }
  }

  @tailrec
  def Process(str: String, i: Int, p: List[Int], f:Int,res: Int): Int = {
    if (i >= str.length || res < 0) {
      if(f==0) res else -1
    } else {
      if(L.contains(str(i))){
        Process(str,i+1,L.indexOf(str(i))::p,f+1,res+1)
      }else{
        if(p.isEmpty){
          -1
        }else{
          if(p.head == R.indexOf(str(i))){
            Process(str,i+1,p.drop(1),f-1,res-1)
          }else{
            Process(str,i+1,p.drop(1),f-1,res)
          }
        }
      }
    }
  }
}

import util.control.Breaks._
import scala.collection.mutable.Stack

object brackets {
  def main(args: Array[String]) {
    var ans = 0
    val left  = "<{[("
    val right = ">}])"

    val s = scala.io.StdIn.readLine
    var stack = new Stack[Char]
    breakable {
      s.foreach { c =>
        if (left.contains(c)) {
          stack.push(c)
        } else if (right.contains(c)) {
          val pos = right.indexOf(c)
          if (stack.isEmpty) {
            ans = -1
            break
          }
          var tmp = stack.pop
          if (tmp != left(pos)) ans+=1
        }
        //stack.push(_)
      }
    }
    if (ans == -1 || !stack.isEmpty) println("Impossible")
    else println(ans)
  }
}

import util.control.Breaks._
import scala.collection.mutable.Stack

object brackets {
  def main(args: Array[String]) {
    var ans = 0
    val left  = "<{[("
    val right = ">}])"

    val s = scala.io.StdIn.readLine
    var stack = new Stack[Char]
    breakable {
      s.foreach { c =>
        if (left.contains(c)) {
          stack.push(c)
        } else if (right.contains(c)) {
          val pos = right.indexOf(c)
          if (stack.isEmpty) {
            ans = -1
            break
          }
          var tmp = stack.pop
          if (tmp != left(pos)) ans+=1
        }
        //stack.push(_)
      }
    }
    if (ans == -1) println("Impossible")
    else println(ans)
  }
}

import java.util.Scanner
import scala.annotation.tailrec

object Main {
  val L = "<{[("
  val R = ">}])"
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val inStr = scan.nextLine()
    scan.close()

    val res = Process(inStr,0,Nil,0)
    if(res<0){
      print("Impossible")
    }else{
      print(res)
    }
  }

  @tailrec
  def Process(str: String, i: Int, p: List[Int], res: Int): Int = {
    if (i >= str.length || res < 0) {
      res
    } else {
      if(L.contains(str(i))){
        Process(str,i+1,L.indexOf(str(i))::p,res+1)
      }else{
        if(p.isEmpty){
          -1
        }else{
          if(p.head == R.indexOf(str(i))){
            Process(str,i+1,p.drop(1),res-1)
          }else{
            Process(str,i+1,p.drop(1),res)
          }
        }
      }
    }
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println(data.sorted.foldLeft(Set.empty[Int]) {
    case (set, a) if a % k != 0 => set + a
    case (set, a) if !set.contains(a / k) => set + a
    case (set, a) => set
  }.size)
}

import java.util.Scanner

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

object Main {
  val scanner = new Scanner(System.in)
  def main(args: Array[String]): Unit = {
    val Array(n, k) = scanner.nextLine().split(" ").map(_.toInt)
    var v: Vector[Int] = Vector[Int]()
    for(i <- 1 to n) {
      val temp = scanner.nextInt()
      v = v :+ temp
    }
    v = v.sorted
    val s = mutable.HashSet[Int]()
    v.foreach(p => {
      if ((p%k!=0) || !s.contains(p/k)) {
        s.add(p)
      }
    })
    println(s.size)
  }
}

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

import scala.collection.mutable
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C168A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C168A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni()

    val a = na(n).toIndexedSeq.sorted
    val hm = new mutable.HashMap[Int, Boolean]()
    var count = 0
    REP(n) { i =>
      if(a(i) % k == 0) {
        val v = a(i) / k
        if(!hm.contains(v)) {
          count+=1
          hm(a(i)) = true
        }
      } else {
        count+=1
        hm(a(i)) = true
      }
    }
    out.println(count)
  }
}

import collection.mutable.Queue
import java.util.Scanner
import java.io._
import scala.io.Source

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val a=readLine.split(" ").map(_.toLong).sorted
    val set1=a.toSet
    val set2=collection.mutable.Set[Long]()

    a.foreach(i=>{
        if(!set2.contains(i)){
            if(i!=i*k && set1.contains(i*k)) set2+=i*k
        }
    })

    println(set1.size-set2.size)

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println(data.sorted.foldLeft(Set.empty[Int]) {
    case (set, a) if a % k == 0 && !set.contains(a / k) => set + a
    case (set, a)  => set
  }.size)
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C168A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C168A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni().toLong

    a = na(n).toIndexedSeq.sorted
    var mx = -1
    REP(n) { i =>
      var from = i
      var count = 1
      var target = a(from) * k
      while (from < n) {
        val id = bs(from, n-1, target)
        count += (id - from)
        from = id + 1
        target = a(id) * k
      }
      if(mx < count) mx = count
    }
    out.println(mx)
  }

  var a: IndexedSeq[Int] = _

  def bs(from: Int, to: Int, v: Long): Int = {
    var l = from
    var r = to

    while (r - l > 1) {
      val m = l + (r - l) / 2
      if(a(m) >= v) r = m-1
      else l = m
    }
    if(a(r) >= v) l
    else r
  }
}

import collection.mutable.Queue
import java.util.Scanner
import java.io._
import scala.io.Source

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val a=readLine.split(" ").map(_.toLong).sorted
    val set1=a.toSet
    val set2=collection.mutable.Set[Long]()

    a.foreach(i=>{
        if(!set2.contains(i)){
            if(set1.contains(i*k)) set2+=i*k
        }
    })

    println(set1.size-set2.size)

}

import collection.mutable.Queue
import java.util.Scanner
import java.io._
import scala.io.Source

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val a=readLine.split(" ").map(_.toInt).sorted
    val set1=a.toSet
    val set2=collection.mutable.Set[Int]()

    a.foreach(i=>{
        if(!set2.contains(i)){
            if(set1.contains(i*k)) set2+=i*k
        }
    })

    println(set1.size-set2.size)

}

import java.util.Scanner

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

object Main {
  val scanner = new Scanner(System.in)
  def main(args: Array[String]): Unit = {
    val Array(n, k) = scanner.nextLine().split(" ").map(_.toInt)
    var v: Vector[Int] = Vector[Int]()
    for(i <- 1 to n) {
      val temp = scanner.nextInt()
      v = v :+ temp
    }
    v = v.sorted
    val s = mutable.HashSet[Int]()
    v.foreach(p => {
      if (!s.contains(p/k)) {
        s.add(p)
      }
    })
    println(s.size)
  }
}


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

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

  val N = sc.nextInt
  val d = Array.fill(N)(sc.nextInt)
  val s, t = sc.nextInt

  val answer = {
    val d0 = {
      val s0 = s min t
      val t0 = s max t

      for (i <- s0 - 1 until t0 - 1)
      yield d(i)
    }.sum
    val d1 = d.sum - d0
    d0 min d1
  }

  out.println(answer)
  out.close
}

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val t = for (s <- readLine.split(" ")) yield s.toInt
  val Array(_s,_g) = for(s <- readLine.split(" ")) yield s.toInt - 1

  def srt(a: Int, b: Int) = { if(a < b) (a,b) else (b,a) }
  val (s,g) = srt(_s, _g)

  def solve1(i: Int): Int = {
    if(i == g) 0
    else t(i) + solve1(i+1)
  }
  def solve2(i: Int): Int = {
    if(i == g) t(i)
    else t(i) + solve2((i-1+n)%n)
  }
  val (res,_) = srt(solve1(s),solve2((s-1+n)%n))
  println(res)
}

import java.util.StringTokenizer

object _278A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  val s = next.toInt - 1
  val t = next.toInt - 1
  if (s == t) println(0)
  else {
    def f(x: Int): Int =
      if (x == t) 0
      else f((x + 1) % n) + a(x)

    def g(x: Int): Int =
      if (x == t) 0
      else g((x + n - 1) % n) + a((x + n - 1) % n)

    println(f(s) min g(s))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val d = in.next().split(" ").map(_.toInt)
  val Array(s, t) = in.next().split(" ").map(_.toInt - 1).sorted
  val n1 = d.slice(s, s + t - s).sum
  val n2 = d.take(s).sum + d.drop(t).sum
  println(Math.min(n1, n2))

}

object A278 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val dist = readInts(n)
    var Array(s, t) = readInts(2)
    var clockWise = 0
    if (t >= s) {
      var loc = s
      while (loc != t) {
        clockWise += dist(loc - 1)
        loc += 1
      }
    } else {
      var loc = s
      while (loc != n + 1) {
        clockWise += dist(loc - 1)
        loc += 1
      }
      loc = 1
      while (loc != t) {
        clockWise += dist(loc - 1)
        loc += 1
      }
    }
    var antiClockWise = 0
    var temp = s
    s = t
    t = temp
    if (t >= s) {
      var loc = s
      while (loc != t) {
        antiClockWise += dist(loc - 1)
        loc += 1
      }
    } else {
      var loc = s
      while (loc != n + 1) {
        antiClockWise += dist(loc - 1)
        loc += 1
      }
      loc = 1
      while (loc != t) {
        antiClockWise += dist(loc - 1)
        loc += 1
      }
    }
    println(math.min(clockWise, antiClockWise))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

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

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

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

}

import annotation.tailrec
import java.io._

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

  val n = readInt
  val a = readInts
  val Array(s, t) = readInts
  val sum = a.zip(1 to n).filter {
    case (_, pos) => pos >= s.min(t) && pos < s.max(t)
  }.map(_._1).sum
  def ans = sum.min(a.sum - sum)

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

object Main {
  def main(args: Array[String]) {
    val num = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val ind = readLine().split(" ").map(_.toInt).sorted
    val direct = a.drop(ind(0) - 1).take(ind(1) - ind(0)).sum
    val indirect = a.sum - direct
    println(direct.min(indirect))
  }
}

import Array._

object main extends App with fastIO {

  var Array(n) = readLine split(" ") map(_.toInt)
  var a = readLine split(" ") map(_.toInt)
  var Array(s, t) = readLine split (" ") map(_.toInt) sorted

  val value = a.drop(s - 1).take(t - s).sum
  println((a.sum - value) min value)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

import java.util.Scanner;
object runner {
def main(args:Array[String]){
var sc =new Scanner(System.in);
        var a=sc.nextInt();
       var i=0;
       val mas=new Array[Int](a);
       var sum=0;
        while(i<a)
        {
            mas(i)=sc.nextInt();
            sum+=mas(i);
            i+=1;
        }
        var j=sc.nextInt();
       var l=sc.nextInt();
        if(j>l){var k=j;j=l;l=k;}
       var x=0;
        if(j!=l){
        while(j<l)
        {
            x+=mas(j-1);
            j+=1;
        }
        System.out.println(Math.min(x,sum-x));}else{System.out.println(0);}
        }
    }

object runner {
def main(args:Array[String]){
var liner=readInt();
var read=readLine().split(" ");
var re=readLine().split(" ");
var first=re(0).toInt;
var second=re(1).toInt;
var sum=0;
for(i<-first-1 to second-2){
  sum+=read(i).toInt;
}
if(first==liner){
  var path=read(first-1).toInt;
  for(i<-second-1 to first-2){
    sum+=read(i).toInt;
  }
  if(sum>path){
    sum=path;
  }
}
println(sum);
}
}

object runner {
def main(args:Array[String]){
var liner=readInt();
var read=readLine().split(" ");
var re=readLine().split(" ");
var first=re(0).toInt;
var second=re(1).toInt;
var sum=0;
if(first<second){
for(i<-first-1 to second-2){
  sum+=read(i).toInt;
}
}else{
  for(i<-second-1 to first-2){
    sum+=read(i).toInt;
  }
  if(first==liner){
  var path=read(first-1).toInt;
  if(sum>path){
    sum=path;
  }
}

}

println(sum);
}
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (l, r) = (1 to n).foldLeft(-2l * 1E9.toLong, 2l * 1E9.toLong) {
    case ((left, right), _) if left > right => (left, right)
    case ((left, right), _) =>
      in.next().split(' ') match {
        case Array(">", b, "N") => (left, Math.min(right, b.toLong))
        case Array("<=", b, "Y") => (left, Math.min(right, b.toLong))
        case Array("<", b, "N") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "Y") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "N") => (left, Math.min(right, b.toLong - 1))
        case Array("<", b, "Y") => (left, Math.min(right, b.toLong - 1))
        case Array("<=", b, "N") => (Math.max(left, b.toLong + 1), right)
        case Array(">", b, "Y") => (Math.max(left, b.toLong + 1), right)
      }
  }
  if (l > r)
    println("Impossible")
  else
    println(l)
}

object A extends App {
	val n = readInt()

	def negOp(op: String) = op match {
		case ">" => "<="
		case ">=" => "<"
		case "<" => ">="
		case "<=" => ">"
	}

	def guess(k: Int, mi: Int, ma: Int): Option[Int] = {
		if(mi > ma) None
		else if (k == 0) Some(mi)
		else {
			val line = readLine()
			val pat = """(>|>=|<|<=)\s(-?\d+)\s(Y|N)""".r
			val pat(op, num, ans) = line
			val op1 = if(ans == "N") negOp(op) else op
			val num1 = num.toInt
			op1 match {
				case ">" => guess(k - 1, math.max(mi, num1 + 1), ma)
				case ">=" => guess(k - 1, math.max(mi, num1), ma)
				case "<" => guess(k - 1, mi, math.min(ma, num1 - 1))
				case "<=" => guess(k - 1, mi, math.min(ma, num1))
			}
		}
	}

	guess(n, -2000000000, 2000000000) match {
		case Some(z) => println(z)
		case None => println("Impossible")
	}
}

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    var left = -2000000000
    var right = 2000000000
    for (i <- 1 to n) {
      val Array(sign, x_str, answer) = readLine().split(' ')
      val x = x_str.toInt
      sign match {
        case ">" => {
          answer match {
            case "Y" => left = max(x + 1, left)
            case "N" => right = min(x, right)
          }
        }
        case ">=" => {
          answer match {
            case "Y" => left = max(x, left)
            case "N" => right = min(x - 1, right)
          }
        }
        case "<" => {
          answer match {
            case "Y" => right = min(x - 1, right)
            case "N" => left = max(x, left)
          }
        }
        case "<=" => {
          answer match {
            case "Y" => right = min(x, right)
            case "N" => left = max(x + 1, left)
          }
        }
      }
      if (left > right) {
        println("Impossible")
        return
      }
    }
    println(left)
  }

  def min(x: Int, y: Int) = if (x < y) x else y

  def max(x: Int, y: Int) = if (x > y) x else y
}

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    var left = -2000000001
    var right = 2000000001
    for (i <- 1 to n) {
      val Array(sign, x_str, answer) = readLine().split(' ')
      val x = x_str.toInt
      sign match {
        case ">" => {
          answer match {
            case "Y" => left = max(x + 1, left)
            case "N" => right = min(x, right)
          }
        }
        case ">=" => {
          answer match {
            case "Y" => left = max(x, left)
            case "N" => right = min(x - 1, right)
          }
        }
        case "<" => {
          answer match {
            case "Y" => right = min(x - 1, right)
            case "N" => left = max(x, left)
          }
        }
        case "<=" => {
          answer match {
            case "Y" => right = min(x, right)
            case "N" => left = max(x + 1, left)
          }
        }
      }
      if (left > right) {
        println("Impossible")
        return
      }
    }
    println(left)
  }

  def min(x: Int, y: Int) = if (x < y) x else y

  def max(x: Int, y: Int) = if (x > y) x else y
}

object A extends App {
	val n = readInt()

	def negOp(op: String) = op match {
		case ">" => "<="
		case ">=" => "<"
		case "<" => ">="
		case "<=" => ">"
	}

	def guess(k: Int, mi: Int, ma: Int): Option[Int] = {
		if(mi > ma) None
		else if (k == 0) Some(mi)
		else {
			val line = readLine()
			val pat = """(>|>=|<|<=)\s(-?\d+)\s(Y|N)""".r
			val pat(op, num, ans) = line
			val op1 = if(ans == "N") negOp(op) else op
			val num1 = num.toInt
			op1 match {
				case ">" => guess(k - 1, num1 + 1, ma)
				case ">=" => guess(k - 1, num1, ma)
				case "<" => guess(k - 1, mi, num1 - 1)
				case "<=" => guess(k - 1, mi, num1)
			}
		}
	}

	guess(n, -2000000000, 2000000000) match {
		case Some(z) => println(z)
		case None => println("Impossible")
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (l, r) = (1 to n).foldLeft(-2l * 10E9.toLong, 2l * 10E9.toLong) {
    case ((left, right), _) if left > right => (left, right)
    case ((left, right), _) =>
      in.next().split(' ') match {
        case Array(">", b, "N") => (left, Math.min(right, b.toLong))
        case Array("<=", b, "Y") => (left, Math.min(right, b.toLong))
        case Array("<", b, "N") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "Y") => (Math.max(left, b.toLong), right)
        case Array(">=", b, "N") => (left, Math.min(right, b.toLong - 1))
        case Array("<", b, "Y") => (left, Math.min(right, b.toLong - 1))
        case Array("<=", b, "N") => (Math.max(left, b.toLong + 1), right)
        case Array(">", b, "Y") => (Math.max(left, b.toLong + 1), right)
      }
  }
  if (l > r)
    println("Impossible")
  else
    println(l)
}


import java.util.Scanner

import scala.collection.mutable

/**
 * Created by Kuang.Ru on 14-9-17.
 */
object A443 extends App {
  val sc = new Scanner(System.in)
  val letters = sc.nextLine()
  val letterSet = new mutable.HashSet[Char]()

  letters.toCharArray.foreach((c: Char) => {
    if (c <= 'z' && c >= 'a') {
      letterSet += c
    }
  })

  println(letterSet.size)
}

import scala.io.StdIn._

object Main extends App {
  val rgx = """\w""".r
  val input = readLine().split("")
  val chars = input.filter(rgx.pattern.matcher(_).matches())
  val ans = chars.toSet.size
  println(ans)
}

object Main extends App{
  val in=readLine
  println(in.filter(t => t >='a'&& t <='z').distinct.length)
}

import scala.io.StdIn

object Task443A {
	def main(args: Array[String]) {
		val s = StdIn.readLine()
		if (s.length == 2) println(0)
		else println(s.substring(1, s.length - 1).split(", ").toSet.size)
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  println(in.next().filter(t => t >= 'a' && t <= 'z').distinct.length)
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println(readLine.drop(1).dropRight(1).split(",").filter(t=>t.trim.length!=0).map(_.trim).toSet.size)
  }
}

object A443 {
  @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 input = scala.io.StdIn.readLine

    println(input.drop(1).dropRight(1).split(", ").dropWhile(_.isEmpty).toSet.size)
  }
}

object AntonAndLetters {

	def main (args: Array[String]) {
  		val scanner = new java.util.Scanner(System.in);
  		val input = scanner.nextLine();
  		val inputAsArray = input.split(Array(',', ' ', '}','{'));
  		println(Math.max(0,inputAsArray.toSet.size-1));
	}
}

object Main extends App {
  override def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val str = cin.nextLine()
    def solve(c: Char, ans: Int): Int =
      if (c > 'z') ans
      else if (str.contains(c)) solve((c + 1).toChar, ans + 1)
      else solve((c + 1).toChar, ans)
    println(solve('a', 0))
  }
}

import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
    val s = readLine.toString.replaceAll("[{}, ]","")
    println(s.distinct.size)
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object AntonLetters {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val s = readLine
     if (s == "{}") println("0") else
     println(s.tail.reverse.tail.reverse.split(", ").toSet.size)

   }

}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    println(StdIn.readLine().filter(t => t >= 'a' && t <= 'z' ).distinct.length)

  }

}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    println(StdIn.readLine().
      replace("{","").replace("}", "").split(", ").
      map(_.toCharArray).flatten.toSet.size)

  }

}

import java.io._
import util.control.Breaks._

object Solution extends App {
  val s = readLine.split("{}, ".toArray).filter(_!="")

  println(s.toSet.size)
}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
    val input = br.readLine()
  val r = input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',')
  if (r.isEmpty) println(0) else println(r.split(" ").toList.toSet.size)

}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println(readLine.drop(1).dropRight(1).split(",").map(_.trim).toSet.size)
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object AntonLetters {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     println(readLine.tail.reverse.tail.reverse.split(", ").toSet.size)

   }

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
  val input = br.readLine()
  println(input.filter(_ == '{').filter(_ == '}').split(" ").toList.toSet.size)

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
  val input = br.readLine()
  println(input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',').split(" ").toList.toSet.size)

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
    val input = br.readLine()
  val r = input.filterNot(_ == '{').filterNot(_ == '}').filterNot(_ == ',')
  if (r.isEmpty) println(0) else r.split(" ").toList.toSet.size

}

object t443a extends App {

  import java.io.{BufferedReader, InputStreamReader}

  val br = new BufferedReader(new InputStreamReader(System.in))
  val input = br.readLine()
  println(input.split(" ").toList.toSet.size - 2)

}


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

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

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

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

  def solve(): Unit = {
    val N, M, K, L = nl()
    val x = (L + K - 1) / M + 1
    if (x == 0 || BigInt(M) * x > N) {
      out.println(-1)
    } else {
      out.println(x)
    }
  }

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

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

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

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

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

object CF_518_2_A {
  def solve(N: Long, // number of coin types
            M: Long, // number of friends
            K: Long, // how many types Ivan has
            L: Long  // min number of new types
           ): Long = {
    val maxTypes = (N/M)*M
    val needed = K + L
    if (needed > maxTypes) -1
    else  Utility.longCeil(needed, M)

  }

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val solution = solve(io.long, io.long, io.long, io.long)
    println(solution)
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a + b - 1) / b
      def longCeil(a: Long, b: Long) = (a + b - 1) / b
    }

}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  val red = line.count(_ == 'r')
  val black = n - red
  val redOdd = line.indices.count(i => i % 2 == 1 && line(i) == 'r')
  val redEven = red - redOdd
  val blackOdd = line.indices.count(i => i % 2 == 1 && line(i) == 'b')
  val blackEven = black - blackOdd
  val redFirst = Math.max(redOdd, blackEven)
  val blackFirst = Math.max(blackOdd, redEven)
  println(Math.min(redFirst, blackFirst))
}

import scala.io.StdIn._
object ProblemB extends App {
  val n = readInt()
  val s = readLine().view.zipWithIndex

  val rb = s.foldLeft((0, 0))((acc, t) =>
    (if ((t._2 % 2 == 0 && t._1 == 'r') || t._2 % 2 == 1) acc._1 else acc._1 + 1,
    if ((t._2 % 2 == 1 && t._1 == 'b') || t._2 % 2 == 0) acc._2 else acc._2 + 1)
  )

  val rb2 = s.foldLeft((0, 0))((acc, t) =>
    (if ((t._2 % 2 == 0 && t._1 == 'b') || t._2 % 2 == 1) acc._1 else acc._1 + 1,
      if ((t._2 % 2 == 1 && t._1 == 'r') || t._2 % 2 == 0) acc._2 else acc._2 + 1)
  )

  val solution1 = math.abs(rb._1 - rb._2) + math.min(rb._1, rb._2)
  val solution2 = math.abs(rb2._1 - rb2._2) + math.min(rb2._1, rb2._2)
  println(math.min(solution1, solution2))
}


object Main {
    def main(args: Array[String]) = {
        val Array(n, q, k) = readLine().split("\\s+").map(_.toInt)
        val a = readLine().split("\\s+").map(_.toInt)
        for (i <- 1 to q){
            // val l = sc.nextInt()
            // val r = sc.nextInt()
            var Array(l, r) = readLine().split("\\s+").map(_.toInt)
            l -= 1
            r -= 1
            val len = r - l + 1
            println((k - len) * 2 - (a(l) - 1) - (k - a(r)))
            // println(k - r + l)
        }
    }
}

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

object BReplaceandKeepSorted {
  def solve(k: Int, initList: Array[Int], s: Int, f: Int): Int = {
    if (s == f) return k - 1
//    var c = 0
//    for (i <- s until f - 1) {
//      c += (initList(i+1) - initList(i-1) - 2)
//    }
//    c + (initList(s) - 2) + (k + 1 - initList(f - 2) - 2)
    (f - s + 1) * (-2) + k + 1 + initList(f - 1) - initList(s-1)
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//            val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//              ("6 5 10\n2 4 6 7 8 9\n1 4\n1 2\n3 5\n1 6\n5 5").getBytes)))
    val n::q::k::Nil = file.readLine.split(" ").map(_.toInt).toList
    val as = file.readLine.split(" ").map(_.toInt)
    var i = 0
    while (i < q) {
      val l::r::Nil = file.readLine.split(" ").map(_.toInt).toList
      println(solve(k, as, l, r))
      i += 1
    }
  }
}


object B extends App {

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

  val Array(n, m) = readInts(2)
  val as = Array.fill(n){ readInts(m) }
  var can = false

  for (i <- 0 until m) {
    for (j <- i + 1 until m) {
      var ok = true
      for (row <- as) {
        var cntWrong1, cntWrong2 = 0
        for (c <- 0 until m) {
          if (c != i && c != j && row(c) != c + 1) cntWrong1 += 1
          if (row(c) != c + 1) cntWrong2 += 1
        }
        if (!((cntWrong1 == 0 && cntWrong2 == 2) ||
          (cntWrong1 == 0 && cntWrong2 == 0) ||
          (cntWrong1 == 2 && cntWrong2 == 4 && row(i) == j + 1 && row(j) == i + 1) ||
          (cntWrong1 == 1 && cntWrong2 == 3))) ok = false
        //if (ok) println(i, j, row.mkString(" "), cntWrong1, cntWrong2)
      }
      if (ok) {
        can = true
        //println(i, j)
      }
    }
  }

  var ok = true
  for (row <- as) {
    var cntWrong = 0
    for (c <- 0 until m) {
      if (row(c) != c + 1) cntWrong += 1
    }
    if (cntWrong != 0 && cntWrong != 2) ok = false
  }
  if (ok) can = true

  println(if (can) "YES" else "NO")
}

import java.io._

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

  def processStdInOut(): Unit = {
    val src = io.Source.fromInputStream(System.in)
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
        bw.close()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line = lines.next()
    val strings = line.split(' ')
    val n = strings(0).toInt
    val m = strings(1).toInt
    val table = Array.ofDim[Int](n, m)
    for (r <- 0 until n) {
      val row = lines.next()
      val entries = row.split(' ').map(_.toInt - 1)  // i.e. make zero-based
      table(r) = entries
    }

    val hasSolution = solve(n, m, table)
    if (hasSolution) { bw.write("YES") } else {bw.write("NO") }
    bw.newLine()
  }

  def solve(n: Int, m: Int, table: Array[Array[Int]]): Boolean = {
    val indexCombinations = (1 until m).flatMap { col => (0 until col).map( (_, col)) }

    def isRowSorted(row: Array[Int]): Boolean = row.zipWithIndex.forall(p => p._1 == p._2)

    def swapEntriesInPlace(row: Array[Int], swap: (Int, Int)): Unit = {
      val (col1, col2) = swap
      val firstEntry = row(col1)
      row(col1) = row(col2)
      row(col2) = firstEntry
    }

    def isSortedAfterSwaps(row: Array[Int], swaps: (Int, Int)* ): Boolean = {
      val newRow = row.clone()
      swaps.foreach(swapEntriesInPlace(newRow, _))
      isRowSorted(newRow)
    }

    def columnSwapHasSolution(colSwap: (Int, Int)): Boolean = {
      def rowCanBeOrdered(rowIndex: Int): Boolean = {
        val rowPrior = table(rowIndex)
        def entriesCanBeSwapped(entrySwap: (Int, Int)): Boolean = {
          // Either do the column swap before or after:
          isSortedAfterSwaps(rowPrior, colSwap, entrySwap) ||
            isSortedAfterSwaps(rowPrior, entrySwap, colSwap)
        }
        // See if column swap is sufficient to reorder, else try swapping each combination of entries...
        val rowHasSolution = isSortedAfterSwaps(rowPrior, colSwap) ||
          indexCombinations.exists(entriesCanBeSwapped(_))
        rowHasSolution
      }
      val hasSolution = (0 until n).forall(rowCanBeOrdered)
      hasSolution
    }

    def isThereASolutionWithNoColumnSwap(): Boolean = {
      def rowCanBeOrdered(rowIndex: Int): Boolean = {
        val rowPrior = table(rowIndex)
        // See if row is already sorted, else try swapping each combination of entries...
        val rowHasSolution = isRowSorted(rowPrior) || indexCombinations.exists(isSortedAfterSwaps(rowPrior, _))
        rowHasSolution
      }
      val hasSolution = (0 until n).forall(rowCanBeOrdered)
      hasSolution
    }

    isThereASolutionWithNoColumnSwap() || indexCombinations.exists(columnSwapHasSolution)
  }
}

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

object _724B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, m = read[Int]
    val table = Vector.fill(n)(read[Array, Int](m))
    val idealRow = (1 to m).toIndexedSeq

    def isOkay(i: Int, j: Int) = table forall { row =>
      row.swap(i, j)
      val ans = row.indices.count(k => row(k) != idealRow(k)) <= 2
      row.swap(j, i)
      ans
    }

    val f = Function.tupled(isOkay _)
    val ans = (m X m).exists(f)

    write(ans.toEnglish)
  }
}
/****************************[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)
    def swap(i: Int, j: Int): Unit = {
      val t = a(i)
      a(i) = a(j)
      a(j) = t
    }
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def 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)
  }
  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
  }
  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 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")

  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 = "\n"): 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
      }
    }
  }
}

object B extends App {

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

  val Array(n, m) = readInts(2)
  val as = Array.fill(n){ readInts(m) }
  var can = false

  for (i <- 0 until m) {
    for (j <- i + 1 until m) {
      var ok = true
      for (row <- as) {
        var cntWrong = 0
        for (c <- 0 until m) {
          if (c != i && c != j && row(c) != c + 1) cntWrong += 1
        }
        if (cntWrong != 0 && cntWrong != 2 &&
          (cntWrong != 1 || row(i) == i + 1 || row(j) == j + 1)) ok = false
      }
      if (ok) can = true
    }
  }

  println(if (can) "YES" else "NO")
}


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

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

  def main (args: Array[String]){
    val n, r = in.next().toInt
    val x = new Array[Int](n+1)
    for (i <- 1 to n)
      x(i) = in.next().toInt

    //
    def calcY(x: Int, p: (Double, Double)): Double = { // retrun y
      val dia = 2 * r
      val (px, py) = p
      val hoge = x.toDouble - px
      sqrt(dia*dia - hoge*hoge) + py
    }

    val ans = new Array[Double](n+1)

    val centers = new Array[(Double, Double)](n+1)
    val axisX = new Array[Int](1000 + r + 1) // has Graph-number

    for(graphNum <- 1 to n) {
      val nowX: Int = x(graphNum)
      val xrange = (0 max (nowX - r)) to (nowX + r)

      var pos: (Double, Double) = (nowX, r)
      for (x <- xrange) {
        if (axisX(x) > 0){
          val viewGraph = axisX(x)
          val viewPos = centers(viewGraph)

          val nowY: Double = calcY(nowX, viewPos)
          if(nowY > pos._2)
            pos = (nowX, nowY)
        }
      }

      // post-process
      centers(graphNum) = pos
      for (x <- xrange) {
        axisX(x) = graphNum
      }
      ans(graphNum) = pos._2
    }

    for (i <- 1 to n-1) {
      pw.print(ans(i) + " ")
    }
    pw.println(ans(n))
    pw.flush()
  }
}

class InputReader(stream: InputStream) {
  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 C extends App {

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

  val Array(n, r) = readInts(2)
  val xs = readInts(n)

  val ys = Array.fill(n){ r.toDouble }

  def intersects(x1: Int, x2: Int): Boolean = {
    Math.abs(x1 - x2) <= 2 * r
  }

  def sqr(a: Double) = a * a

  def stopsAt(x1: Int, j: Int): Double = {
    val y0 = ys(j)
    val dY = Math.sqrt(sqr(2 * r) - sqr(x1 - xs(j)))
    y0 + dY
  }

  for (i <- 1 until n) {

    val stopYs = for {
      j <- 0 until i
      if intersects(xs(i), xs(j))
    } yield stopsAt(xs(i), j)

    ys(i) = if (stopYs.isEmpty) r.toDouble else stopYs.max
  }

  println(ys.mkString(" "))
}

object C extends App {
  val e = scala.math.pow(10, -6)

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

  val R = 2.0 * r

  def y2(x1: Int, y1: Double, x2: Int): Double = {
    val t = scala.math.sqrt((R - x1 + x2) * (R + x1 - x2))
    (y1 - t) max (y1 + t)
  }

  def r(x: Int, a: Array[(Int, Double)]): Array[(Int, Double)] =
    a.filter(t => scala.math.abs(t._1 - x) <= R)

  def g(x: Array[Int], a: Array[(Int, Double)] = Array.empty): Array[Double] =
    if (x.isEmpty) a.map(_._2).reverse
    else {
      val y = r(x.head, a).map(t => y2(t._1, t._2, x.head))
      if (y.isEmpty) g(x.tail, (x.head, r.toDouble) +: a)
      else g(x.tail, (x.head, y.max) +: a)
    }

  println(g(x).mkString(" "))
}

object CF908C extends App {

  val sc = new java.util.Scanner(System.in)
  val discs, radius = sc.nextInt

  val result = append(0, Nil)

  println(result map (c => c._2) mkString " ")

  def append(i: Int, circles: List[(Int, Double)]):  List[(Int, Double)] = {

    if (i == discs) return circles
    val cs = append(i+1, circles)
    val nx = sc.nextInt
    if (cs.isEmpty) cs :+ (nx, radius.toDouble)  else cs :+ (nx, findCircle(nx, cs))
  }

  def findCircle(x: Int, circles: List[(Int, Double)]): Double = {
    var result = radius.toDouble
    //println("X: " + x)
    for (c <- circles.sortWith(_._2 > _._2)) {
      //println("X: %d Y:%f".format(c._1, c._2))
      val xdiff = Math.abs(x - c._1)
      //println("XD: " + xdiff)
      if (xdiff <= radius * 2){
        val ydiff = Math.sqrt(Math.pow(radius * 2, 2) - Math.pow(xdiff, 2))
        //println("YD: " +ydiff)
        result = Math.max(result, c._2 + ydiff)
      }
    }
    return result
  }
}

object CF908C extends App {

  val sc = new java.util.Scanner(System.in)
  val discs, radius = sc.nextInt

  val result = append(0, Nil)

  println(result map (c => c._2) mkString " ")

  def append(i: Int, circles: List[(Int, Double)]):  List[(Int, Double)] = {

    if (i == discs) return circles
    val cs = append(i+1, circles)
    val nx = sc.nextInt
    if (cs.isEmpty) cs :+ (nx, radius.toDouble)  else cs :+ (nx, findCircle(nx, cs))
  }

  def findCircle(x: Int, circles: List[(Int, Double)]): Double = {
    //println("X: " + x)
    for (c <- circles.sortWith(_._2 > _._2)) {
      //println("X: %d Y:%f".format(c._1, c._2))
      val xdiff = Math.abs(x - c._1)
      //println("XD: " + xdiff)
      if (xdiff <= radius * 2){
        val ydiff = Math.sqrt(Math.pow(radius * 2, 2) - Math.pow(xdiff, 2))
        //println("YD: " +ydiff)
        return c._2 + ydiff
      }
    }
    0.0 // something wrong
  }
}


import scala.collection.mutable

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

  val n = nextInt
  val cs = Array.fill(3)(nextLongs(n))
  val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}
  for (_ <- 2 to n) {
    val u, v = nextInt - 1
    adjBuilders(u) += v
    adjBuilders(v) += u
  }
  val adjs = adjBuilders.map(_.result())
  var bad = false

  val depths = Array.ofDim[Int](n)
  def dfs(u: Int, prev: Int, depth: Int): Unit = {
    depths(u) = depth % 3
    var i = 0
    if (adjs(u).length > 2) bad = true
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }
  }

  val leaf = adjs.indexWhere(_.length == 1)
  dfs(leaf, -1, 0)

  if (bad) out.println(-1)
  else {
    //println(depths.mkString(" "))
    val colors = Array(0, 1, 2)
    var minCost = Long.MaxValue
    var bestColoring = colors
    for (coloring <- colors.permutations) {
      var cost = 0L
      for (i <- 0 until n) {
        cost += cs(coloring(depths(i)))(i)
      }
      if (cost < minCost) {
        minCost = cost
        bestColoring = coloring
      }
    }

    val res = depths.map(bestColoring(_) + 1)

    out.println(minCost)
    out.println(res.mkString(" "))
  }
  out.flush()

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

//package codeforces.contest1244

object PaintTheTree {

  type Graph = Map[Int, Set[Int]]

  def update(graph: Graph, x: Int, y: Int): Graph = {
    val setX: Set[Int] = graph.withDefaultValue(Set.empty)(x)
    val setY: Set[Int] = graph.withDefaultValue(Set.empty)(y)
    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def linearize(graph: Graph): List[Int] = {

    @scala.annotation.tailrec
    def loop(node: Int, acc: List[Int]): List[Int] = {

      acc match {
        case Nil => loop(graph(node).head, node :: acc)
        case h :: _ =>
          graph(node).find(_ != h) match {
            case Some(next) => loop(next, node :: acc)
            case None       => node :: acc
          }
      }
    }

    loop(graph.find(_._2.size == 1).get._1, Nil)
  }

  def expandListToSize(n: Int, ls: List[Int]): List[Int] = {
    val size = ls.length
    (1 to n / size + 1).toList.flatMap(_ => ls).take(n)
  }

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

    val getColor = Seq(colorA, colorB, colorC)

    val graph: Graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { (acc, _) =>
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      update(acc, x, y)
    }

    def colorToValue(color: Int, node: Int): Long = getColor(color - 1)(node - 1).toLong

    println {
      if (graph.values.forall(_.size <= 2)) {

        val seq = linearize(graph)

        val solutionList = List(
          expandListToSize(n, List(1, 2, 3)),
          expandListToSize(n, List(1, 3, 2)),
          expandListToSize(n, List(2, 1, 3)),
          expandListToSize(n, List(2, 3, 1)),
          expandListToSize(n, List(3, 2, 1)),
          expandListToSize(n, List(3, 1, 2))
        )

        val (min, list) = solutionList
          .map { ls =>
            val zipped = ls.zip(seq)
            (zipped.map((colorToValue _).tupled).sum, zipped.sortBy(_._2).map(_._1))
          }
          .minBy(_._1)

        min + "\n" + list.mkString(" ")
      } else -1
    }

  }
}

//package codeforces.contest1244

object PaintTheTree {

  type Graph = Map[Int, Set[Int]]

  def update(graph: Graph, x: Int, y: Int): Graph = {
    val setX: Set[Int] = graph.withDefaultValue(Set.empty)(x)
    val setY: Set[Int] = graph.withDefaultValue(Set.empty)(y)
    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def linearize(graph: Graph): List[Int] = {

    @scala.annotation.tailrec
    def loop(node: Int, acc: List[Int]): List[Int] = {

      acc match {
        case Nil => loop(graph(node).head, node :: acc)
        case h :: _ =>
          graph(node).find(_ != h) match {
            case Some(next) => loop(next, node :: acc)
            case None       => node :: acc
          }
      }
    }

    loop(graph.find(_._2.size == 1).get._1, Nil)
  }

  def expandListToSize(n: Int, ls: List[Int]): List[Int] = {
    val size = ls.length
    (1 to n / size + 1).toList.flatMap(_ => ls).take(n)
  }

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

    val getColor = Seq(colorA, colorB, colorC)

    val graph: Graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { (acc, _) =>
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      update(acc, x, y)
    }

    def colorToValue(color: Int, node: Int) = getColor(color - 1)(node - 1)

    println {
      if (graph.values.forall(_.size <= 2)) {

        val seq = linearize(graph)

        val solutionList = List(
          expandListToSize(n, List(1, 2, 3)),
          expandListToSize(n, List(1, 3, 2)),
          expandListToSize(n, List(2, 1, 3)),
          expandListToSize(n, List(2, 3, 1)),
          expandListToSize(n, List(3, 2, 1)),
          expandListToSize(n, List(3, 1, 2))
        )

        val (min, list) = solutionList
          .map { ls =>
            val zipped = ls.zip(seq)
            (zipped.map((colorToValue _).tupled).sum, zipped.sortBy(_._2).map(_._1))
          }
          .minBy(_._1)

        min + "\n" + list.mkString(" ")
      } else -1
    }

  }
}


object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Long) : Long = {
            if (p == s.size) {
                if (d == 0) c else -1
            } else if (s(p) == '(') {
                cost(p + 1, d + 1, c)
            } else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    if (q.isEmpty) return -1
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        val c = cost(0, 0, 0L)
        println(c)
        if (c != -1) println(s.mkString)
    }
}

object cf3D extends App {
  val s = readLine.toArray
  val q = collection.mutable.PriorityQueue[(Int, Int)]()
  def cost(p : Int, d : Int, c : Long) : Long = {
    if (p == s.size) {
      if (d == 0) c else -1
    } else if (s(p) == '(') {
      cost(p + 1, d + 1, c)
    } else {
      val cN = if (s(p) != '?') c else {
        s(p) = ')'
        val Array(c1, c2) = readLine split " " map {_.toInt}
        q enqueue ((c2 - c1, p))
        c + c2
      }
      if (d > 0) cost(p + 1, d - 1, cN) else {
        if (q.isEmpty) return -1
        val (cm, m) = q.dequeue
        s(m) = '('
        cost(p + 1, d + 1, cN - cm)
      }
    }
  }
  val c = cost(0, 0, 0L)
  println(c)
  if (c != -1) println(s.mkString)
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Int) : Int = {
            if (p == s.size) c else {
                s(p) match {
                    case '(' => cost(p + 1, d + 1, c)
                    case ')' => cost(p + 1, d - 1, c)
                    case '?' => {
                        s(p) = ')'
                        val Array(c1, c2) = readLine split " " map {_.toInt}
                        q enqueue ((c2 - c1, p))
                        if (d > 0) cost(p + 1, d - 1, c + c2) else {
                            val (cm, m) = q.dequeue
                            s(m) = '('
                            cost(p + 1, d + 1, c + c2 - cm)
                        }
                    }
                }
            }
        }
        println(cost(0, 0, 0))
        println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Long) : Long = {
            if (p == s.size) {
                if (d == 0) c else -1
            } else if (s(p) == '(') {
                cost(p + 1, d + 1, c)
            } else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    if (q.isEmpty) return -1
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        println(cost(0, 0, 0L))
        println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Long) : Long = {
            if (p == s.size) c
            else if (s(p) == '(') cost(p + 1, d + 1, c)
            else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        println(cost(0, 0, 0L))
        println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Int) : Int = {
            if (p == s.size) c
            else if (s(p) == '(') cost(p + 1, d + 1, c)
            else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        println(cost(0, 0, 0))
        println(s.mkString)
    }
}