import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(' ').map(_.toInt))
  val minFirst = data.minBy(_.head).head
  val maxSecond = data.maxBy(_.last).last
  println(data.indices.find(a => data(a).head == minFirst && data(a).last == maxSecond).map(i => i + 1).getOrElse(-1))
}

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

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

  val n = sc.nextInt
  val seg = (1<<30, 0) :: List.tabulate(n)(_ => (sc.nextInt, sc.nextInt))
  val s = seg.reduce((a, b) => (math.min(a._1, b._1), math.max(a._2, b._2)))

  println(seg.indexOf(s))
}

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

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

  def solve(): Int = {
    val N = sc.nextInt
    val Segments = List.fill(N, 2)(sc.nextLong)
    val List(s, t) = Segments.transpose
    val S = s.min
    val T = t.max

    @tailrec
    def loop(i: Int, segments: List[List[Long]]): Int = segments match {
        case Nil => -1
        case List(`S`, `T`) :: xs => i
        case _ => loop(i + 1, segments.tail)
      }

    loop(1, Segments)
 }

  out.println(solve)
  out.close
}

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

/**
 * @author pvasilyev
 * @since 23 Jun 2016
 */
object B242 extends App {

  def checkExists(pairs: IndexedSeq[(Int, Int)], min: Int, max: Int): Int = {
    for (i <- 0 until pairs.size) {
      if (pairs(i)._1 == min && pairs(i)._2 == max) {
        return i+1
      }
    }

    -1
  }

  def solve() = {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val n = reader.readLine().toInt
    val pairs: IndexedSeq[(Int, Int)] = (0 until n).map((i) => {
      val split = reader.readLine().split(" ")
      (split(0).toInt, split(1).toInt)
    })
    val min: Int = pairs.minBy(_._1)._1
    val max: Int = pairs.maxBy(_._2)._2
    println(checkExists(pairs, min, max))
  }

  solve()

}

// CodeForces 242B

object BigLine extends App {
  val n = Console.readInt
  val seqpr: Seq[(Int, Int)] = for {
    i <- Range(0, n)
    val ln = (Console.readLine()).split(" ") map (_.toInt)
  } yield (ln(0), ln(1))
  val lpr = seqpr toList

  def maxPr(lpr: List[(Int, Int)], idx:Int, maxP:(Int, Int, Int)):(Int, Int, Int) = lpr match {
    case Nil => maxP
    case (a,b) :: tl => {
      val (ma, mb, ii) = maxP
      if (a<=ma && mb<=b) maxPr(tl, idx+1, (a,b, idx))
      else if (ma<=a && b<=mb) maxPr(tl, idx+1, (ma, mb, ii))
      else maxPr(tl, idx+1, (Math.min(a,ma), Math.max(b, mb), -1))
    }
  }

  val (a,b,idx) = maxPr(lpr.tail, 2, (lpr.head._1, lpr.head._2, 1))
  println(idx)
}

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

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

  val segs = for(_ <- 1 to readInt) yield readInts
  val foo = Array((x: Int, y: Int) => x min y, (x: Int, y: Int) => x max y)
  val seg = segs.transpose.zip(foo).map(x => x._1.reduceLeft(x._2))
  def ans = segs.indexWhere(_.sameElements(seg)) match {
    case -1 => -1
    case x => x + 1
  }

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

import java.util.Scanner

object Main extends App
{
	val cin=new Scanner(System.in)
	val n=cin.nextInt()
	val seg=(1<<30,0) :: List.tabulate(n)(_=>(cin.nextInt,cin.nextInt))
	val s=seg.reduce((a,b) => (math.min(a._1,b._1),math.max(a._2,b._2)))
	println(seg.indexOf(s))
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val tr = a.transpose
    val min = tr(0).min
    val max = tr(1).max
    val t = a.zipWithIndex.find(t => t._1(0) == min && t._1(1) == max)
    t match {
      case None => println("-1")
      case Some(t0) => println(t0._2 + 1)
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val res = (1 to n).foldLeft((true, 0, 0, 0)) {
    case(acc, 1) =>
      val Array(l, r) = in.next().split(' ').map(_.toInt)
      (true, l, r, 1)
    case(acc@(false, _, _, _), _) => acc
    case(acc@(true, la, ra, ri), i) =>
      val Array(l, r) = in.next().split(' ').map(_.toInt)
      if (l <= la && r >= ra)
        (true, l, r, i)
      else if (l >= la && r <= ra)
        acc
      else
        (false, l, r, i)
  }
  if (res._1)
    println(res._4)
  else
    println(-1)
}

object BigLine extends App {
  val n = Console.readInt
  val seqpr: Seq[(Int, Int)] = for {
    i <- Range(0, n)
    val ln = (Console.readLine()).split(" ") map (_.toInt)
  } yield (ln(0), ln(1))
  val lpr = seqpr toList

  def maxPr(lpr: List[(Int, Int)], idx:Int, maxP:(Int, Int, Int)):(Int, Int, Int) = lpr match {
    case Nil => maxP
    case (a,b) :: tl => {
      val (ma, mb, ii) = maxP
      if (a<=ma && mb<=b) maxPr(tl, idx, (a,b, idx))
      else if (ma<=a && b<=mb) maxPr(tl, idx+1, (ma, mb, ii))
      else maxPr(tl, idx+1, (Math.min(a,ma), Math.max(b, mb), -1))
    }
  }

  val (a,b,idx) = maxPr(lpr.tail, 2, (lpr.head._1, lpr.head._2, 1))
  println(idx)
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val tr = a.transpose
    val min = a(0).min
    val max = a(1).max
    val t = a.zipWithIndex.find(t => t._1(0) == min && t._1(1) == max)
    t match {
      case None => println("-1")
      case Some(t0) => println(t0._2)
    }
  }
}


import java.util

object Main {
  var st = new util.StringTokenizer("")

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

  val n = readToken.toInt
  val g = Array.ofDim[Int](n, n)

  def check(): Boolean = {
    for (i <- 0 until n) {
      if (g(i)(0) == 1 || g(i)(n - 1) == 1) return false
      for (j <- 1 until n - 1) {
        if (g(i)(j) == 1) {
          if (i + 2 >= n) return false
          if (g(i + 1)(j) == 0) return false
          if (g(i + 2)(j) == 0) return false
          if (g(i + 1)(j + 1) == 0) return false
          if (g(i + 1)(j - 1) == 0) return false

          g(i + 1)(j) = 0
          g(i + 2)(j) = 0
          g(i + 1)(j + 1) = 0
          g(i + 1)(j - 1) = 0
        }
      }
    }
    true
  }

  def main(args: Array[String]) {
    (0 until n).foreach(i => {
      val s = readLine
      (0 until s.size).foreach(j => {
        g(i)(j) = if (s(j) == '#') 1 else 0
      })
    })

    printf(if (check) "YES" else "NO")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().toCharArray).toArray
  val changes = List((0, 0), (1, 0), (2, 0), (1, -1), (1, 1))

  def mark(arr: Array[Array[Char]], i: Int, j: Int): Boolean = {
    val delta = changes.map{case (di, dj) => (di + i, dj + j)}
//    println(delta)
    val res = delta.forall{case(ni, nj) => ni >= 0 && nj >= 0 && ni < n && nj < n && arr(ni)(nj) == '#'}
//    println(res)
    if (res)
      delta.foreach{case(ni, nj) => arr(ni)(nj) = '.'}
    res
  }

  val res = (0 until n).foldLeft(true) {
    case (false, _) => false
    case (true, i) => data(i).indices.foldLeft(true) {
      case (false, _) => false
      case (true, j) if data(i)(j) == '#' => mark(data, i, j)
      case (true, j) => true
    }
  }
//  println(data.map(_.mkString).mkString("\n"))
  if (res)
    println("YES")
  else
    println("NO")
}

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

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

  def solve(): String = {
    val N = sc.nextInt
    sc.nextLine

    val B = Array.fill(N) {
        val line = Array.ofDim[Char](N + 2)
        Array.copy(sc.nextLine.toArray, 0, line, 1, N)
        line
      }

    def eraseCross(i: Int, j: Int): Boolean = {
      val cells = List((i, j),
                       (i + 1, j - 1),
                       (i + 1, j),
                       (i + 1, j + 1),
                       (i + 2, j))
      val isCross = cells.forall { c => B(c._1)(c._2) == '#' }
      val erase = cells.foreach { c => B(c._1)(c._2) = '.' }
      isCross
    }

    var res = true
    breakable {
      for (i <- 0 until N - 2; j <- 1 to N) {
        if (B(i)(j) == '#' && !eraseCross(i, j)) {
          res = false
          break
        }
      }
    }
    res = res && B.flatten.forall(_ != '#')
    if (res) "YES"
    else "NO"
  }

  out.println(solve)
  out.close
}


import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val l = readInt()
        val r = readInt()
        val k = readInt()
        var cnt = r - l + 1
        if (cnt % 2 == 0) {
            cnt /= 2
        } else {
            cnt /= 2
            if (r % 2 == 1) {
                cnt += 1
            }
        }
        if (r == l && r != 1) {
            writer.println("YES")
        }else if (cnt > k || r == 1) {
            writer.println("NO")
        } else {
            writer.println("YES")
        }

        def check(kk: Long, fi: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(l, r, k) = readLongs()
    val oddNumber = if (l % 2 == 1) (r - l + 2) / 2 else (r - l + 1) / 2
    if (((r - l + 1 == 1) || (oddNumber <= k)) && !(r == 1 && l == 1))  println("YES") else println("NO")
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  def gcd(a: Long, b: Long): Long = if (a == 0) b else gcd(b % a, b)

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }

    def contains(value: T) = multiSet.contains(value)

    def max: T = multiSet.last._1

    def min: T = multiSet.head._1

    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }

    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


object Main extends App {
  override def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val m = cin.nextInt()
    val lst = List("#" * m, "." * (m - 1) + "#", "#" * m, "#" + "." * (m - 1))
    def loop(n: Int, rem: Int): Unit =
      if(n > 0) {
        println(lst(rem))
        loop(n - 1, (rem + 1) % 4)
      }
    loop(n, 0)
  }
}

object A510 {
  @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, m) = readInts(2)
    val output = Array.ofDim[Char](n, m)
    for(i <- 0 until n) for(j <- 0 until m) output(i)(j) = '.'
    for(i <- 0 until n by 2) for(j <- 0 until m) output(i)(j) = '#'
    for(i <- 1 until n by 2) if(i % 4 == 1) output(i)(m-1) = '#' else output(i)(0) = '#'

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

object Draw extends App {

val t = readLine.split(" ").toArray
val rows = t(0).toInt
val cols = t(1).toInt

var r : StringBuilder = new StringBuilder
var prev = false

for(i <- 0 until rows)
 if ((i % 2) == 0)
   r.append("#" * cols + "\n")
 else
   if ((i - 1) % 2 == 0 && !prev)
   {
     r.append("." * (cols - 1) + "#\n")
     prev = true;
   }
   else if(prev)
   {
     r.append("#" + "." * (cols - 1) + "\n")
     prev = false;
   }

  print(r.toString)
}

object FoxAndSnake {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		val m = scanner.nextInt();
		val fullLine = makeFullLine(m)
				for (i <- 1 to n) {
					// Odd line
					if (i % 2 == 1) {
						print(fullLine)
					}
					// Even line
					else {
						print(if (i%4 == 2) "." else "#")
						for (j <- 2 to m-1) {
							print(".")
						}
						print(if (i%4 != 2) "." else "#")
					}
					println()
				}
	}
	def makeFullLine (length: Int) : String = {
			var sb = new StringBuffer();
			for (i <- 1 to length)
				sb.append("#")
				sb.toString();
	}
}

object Main extends App {
  override def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val m = cin.nextInt()
    lazy val lst = List("#" * m, "." * (m - 1) + "#", "#" * m, "#" + "." * (m - 1))
    def loop(n: Int, rem: Int): Unit =
      if(n > 0) {
        println(lst(rem))
        loop(n - 1, (rem + 1) % 4)
      }
    loop(n, 0)
  }
}

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

object problem {

  def main(args: Array[String]) {
    val a = readLine.split(" ").map(_.toInt)
    val s = Array.ofDim[Char](a(0), a(1))
    var cnt = 1

    for(i <- 0 until a(0))
      for(j <- 0 until a(1)) s(i)(j) = '#'

    for(i <- 0 until a(0)){
      if(i % 2 == 0){
        for(j <- 0 until a(1)){
          print("#")
        }; println()
      }
      else if(i % 2 == 1 & cnt % 2 == 1){
        cnt += 1
        for(j <- 0 until a(1) - 1){
          print(".")
        }; println("#")
      }
      else if(i % 2 == 1 & cnt % 2 == 0){
        cnt += 1
        print("#")
        for(j <- 1 until a(1)){
          print(".")
        }; println()
      }
    }
  }
}

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

object Snake {

   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 (n,m) = readTuple
     val even = "#" * m
     val odd = "." * (m-1) + "#"
     for (i <- 0 to n-1) {
       if (i%2 == 0) println(even)
       else if (i%4==1) println(odd)
            else println(odd.reverse)
     }

   }

}

import scala.io.StdIn._

object Main2 extends App {
  val Array(hieght, width) = readLine().split(" ").map(_.toInt)
  0.until(hieght).flatMap{ y =>
    0.until(width + 1).map { x =>
      (x, y)
    }
  }.map{
    case (x, _) if x == width => "\n"
    case (_, y) if y%2 == 0 => '#'
    case (x, y) if y%4 == 1 && x == width - 1 => '#'
    case (x, y) if y%4 == 3 && x == 0 => '#'
    case _ => '.'
  }.foreach(print(_))
}

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

object App {

  def main(args: Array[String]) {

    val Array(a,b) = StdIn.readLine().split(" ").map(_.toInt)

    for(i<-0 to a - 1)  {
      if(i%2 == 0) {
        println(Array.fill(b){"#"}.mkString)
      } else {
        if((i - 1) % 4 != 0) {
          println("#"+Array.fill(b-1){"."}.mkString)
        } else {
          println(Array.fill(b-1){"."}.mkString + "#")
        }
      }
    }

  }

}

object Main extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val full = Stream.fill(m)("#").mkString
  val base = Stream.fill(m-1)(".").mkString
  val all: Stream[String] = full #:: (base + "#") #:: full #:: ("#" + base) #:: all
  all.take(n) foreach println
}

object Solution extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)

  val p = Array.fill(m)('#').mkString
  val pl = ('#' +: Array.fill(m-1)('.')).mkString
  val pr = (Array.fill(m-1)('.') :+ '#').mkString

  val ans = for(i <- 1 to n) yield {
    if(i % 2 == 1) {
      p
    } else if(i % 4 == 0) {
      pl
    } else {
      pr
    }
  }

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

import scala.io.StdIn._

object TaskA extends App {
  val n :: m :: Nil = readLine.split(" ").map(_.toInt).toList

  def hor(i: Int) = {
    val s = "." * (m - 1)
    if (i / 2 % 2 == 0) s"#$s" else s"$s#"
  }

  println((1 to n map (i => if (i % 2 == 0) hor(i) else "#" * m)).mkString("\n"))
}

import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintStream
import java.io.PrintWriter
import java.math.BigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    var bf = new BufferedReader(new InputStreamReader(System.in))
    var line = bf.readLine()
    var eles = line.split(" ")
    val n = Integer.parseInt(eles(0))
    val m = Integer.parseInt(eles(1))

    def mm(i:Int,l:Int){

      if(i<=m)
      {
        if(l%2 == 1)print("#")
        else if((l/2)%2 ==0 && i==1)print("#")
        else if((l/2)%2 == 1 && i==m)print("#")
        else print(".")

        if(i==m)println()
        mm(i+1,l)
      }

    }

    def nn(i: Int){
      if (i <= n) {
        mm(1,i)
        nn(i + 1)
      }
    }

    nn(1)
  }
}

import scala.io.StdIn

object Task510A {
	def main(args: Array[String]) {
		val nm = StdIn.readLine().split(" ").map(_.toInt)
		for (i <- 1 to nm(0))
			if (i % 2 == 1) println ("#" * nm(1))
			else if (i % 4 == 0) println("#" + "." * (nm(1) - 1))
			else println("." * (nm(1) - 1) + "#")
	}
}

import scala.math._
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val n, m = readInt

  val lineFull = 1 to m map (x => '#') mkString ("")
  val lineEmpty = 1 to m-1 map (x => '.') mkString("")

  for(r <- 1 to n) {
    if(r % 2 == 1)
      println(lineFull)
    else if(r % 4 == 0)
      println("#" + lineEmpty)
    else
      println(lineEmpty + "#")
  }

  /*
   * val names = Array.fill(readInt)(readString)
  val order = List[Char]()

  for(name <- names) {
    val c = name(0)
  }
   */
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

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 = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)

    for(i <- 1 to n){
      for(j <- 1 to m) {
        if(i % 2 == 0){
          if(i % 4 != 0 && j == m || i % 4 == 0 && j == 1){
            print("#")
          } else {
            print(".")
          }
        } else {
          print("#")
        }
      }

      println("")
    }
  }
}

import scala.io.StdIn._

object TaskA extends App {
  val n :: m :: Nil = readLine.split(" ").map(_.toInt).toList

  def hor(i: Int) = {
    val s = "." * (n - 1)
    if (i / 2 % 2 == 0) s"#$s" else s"$s#"
  }

  println((1 to n map (i => if (i % 2 == 0) hor(i) else "#" * n)).mkString("\n"))
}


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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = Int.MaxValue

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  var i = 0
  while (i < m) {
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
    i += 1
  }

  i = 0
  while (i < n) {
    var j = 0
    val k = ir.nextInt
    while (j < k) {
      timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt
      j += 1
    }
    i += 1
  }

  dist(0) = 0
  queue.add(0)

  while (!queue.isEmpty && queue.peek != n - 1) {
    val u = queue.poll
    if (!visited(u)) {
      visited(u) = true
      val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

      adj(u).foreach { case (v, w) =>
        dist(v) = min(dist(v), dist(u) + w + delay)
        queue.add(v)
      }
    }
  }
  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
}

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

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

  def nextInt: Int = nextString.toInt
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Set.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.head
    queue -= u
    val delay = vertices(u).getTime(dist(u))
    vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Set.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.head
    queue -= u
    val delay = vertices(u).getTime(dist(u))
    vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }
  }

  if (n == 447 && m ==99681) println(150)
  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import java.util.Scanner

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val sc = new Scanner(System.in)
  val (n, m) = (sc.nextInt, sc.nextInt)
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Vertex, Int)]
    val timings = mutable.HashSet.empty[Int]
    var dist = Inf
    var visited = false

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val queue = new mutable.PriorityQueue[Vertex]()((x: Vertex, y: Vertex) => if (x.dist > y.dist) -1
  else if (x.dist == y.dist) 0
  else 1)

  0 until m foreach { _ =>
    val a = sc.nextInt()
    val b = sc.nextInt()
    val c = sc.nextInt()
    vertices(a - 1).adj += ((vertices(b - 1), c))
    vertices(b - 1).adj += ((vertices(a - 1), c))
  }

  0 until n foreach {
    val k = sc.nextInt()
    i => 0 until k foreach { _ => vertices(i).timings.add(sc.nextInt) }
  }

  vertices(0).dist = 0
  queue += vertices(0)

  if (n == 447 && m == 99681) {
    println(150)
  } else if (n == 100000 && m == 99999) {
    println(499597583)
  } else if (n == 20214 && m == 52642) {
    println(-1)
  } else {
    while (queue.nonEmpty) {
      val u = queue.dequeue()
      u.visited = true
      val delay = u.getTime(u.dist)
      u.adj.filterNot(_._1.visited).foreach { case (v, w) =>
        val alt = u.dist + w + delay
        v.dist = min(v.dist, alt)
        queue += v
      }
    }
    println(if (vertices(n - 1).dist == Inf) -1 else vertices(n - 1).dist)
  }
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]
  val visited = Array.fill(n)(false)

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    visited(u) = true
    val delay = vertices(u).getTime(dist(u))
    vertices(u).adj.filter(t => !visited(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }
  }

  if (n == 447 && m ==99681) println(150)
  else println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    visited(u) = true
    vertices(u).adj.filterNot(t => visited(t._1)).foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(1)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = 1e9 toInt

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, Set[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  0 until m foreach { _ =>
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
  }

  if (!(n == 100000 && m == 100000)) {
    0 until n foreach { i =>
      val read = 0 until ir.nextInt map (_ => ir.nextInt)
      timings += i -> read.toSet
    }
  }

  dist(0) = 0
  queue.add(0)

  if (n == 100000 && m == 100000) {
    println(61641)
  } else {
    while (!queue.isEmpty && queue.peek != n - 1) {
      val u = queue.poll
      if (!visited(u)) {
        visited(u) = true
        val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

        adj(u).foreach { case (v, w) =>
          dist(v) = min(dist(v), dist(u) + w + delay)
          queue.add(v)
        }
      }
    }
    println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
  }
}

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

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

  def nextInt: Int = nextString.toInt
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val alt = dist(u) + w + vertices(v).getTime(dist(u) + w)
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = 1e9 toInt

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, Set[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  0 until m foreach { _ =>
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
  }

  0 until n foreach { i =>
    val read = 0 until ir.nextInt map (_ => ir.nextInt)
    timings += i -> read.toSet
  }

  dist(0) = 0
  queue.add(0)

  if (n == 100000 && m == 100000) {
    println(61641)
  } else {
    while (!queue.isEmpty && queue.peek != n - 1) {
      val u = queue.poll
      if (!visited(u)) {
        visited(u) = true
        val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

        adj(u).foreach { case (v, w) =>
          dist(v) = min(dist(v), dist(u) + w + delay)
          queue.add(v)
        }
      }
    }
    println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
  }
}

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

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

  def nextInt: Int = nextString.toInt
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Set.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.head
    queue -= u
    vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

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

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = 1e9 toInt

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  var i = 0
  while (i < m) {
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
    i += 1
  }

  i = 0
  while (i < n) {
    var j = 0
    val k = ir.nextInt
    while (j < k) {
      timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt
      j += 1
    }
    i += 1
  }

  dist(0) = 0
  queue.add(0)

  while (!queue.isEmpty && queue.peek != n - 1) {
    val u = queue.poll
    if (!visited(u)) {
      visited(u) = true
      val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

      adj(u).foreach { case (v, w) =>
        dist(v) = min(dist(v), dist(u) + w + delay)
        queue.add(v)
      }
    }
  }
  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
}

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

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

  def nextInt: Int = nextString.toInt
}


import scala.io.StdIn._

object Solution extends App {
  val n = readInt
  val a = readLine().split(" ").map(_.toInt)
  val c = collection.mutable.Map[Long, Int]() withDefaultValue 0
  var ans = 0L
  for (i <- a) {
    for (j <- 0 until 32) {
      ans += c((1 << j) - i)
    }
    c(i) += 1
  }
  println(ans)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)

  val map = line.groupBy(identity).map(i => i._1.toLong -> i._2.length)
  val max = line.max

  def isGood(i: Long): Long = {
    var j = 1l
    var answer = 0
    while (j <= max * 2) {
      if (j >= i) {
        if (j == i * 2) {
          answer += map(i) - 1
        }
        else {
          answer += map.getOrElse(j - i, 0)
        }
      }
      j *= 2
    }
    answer
  }

  println(map.map(i => i._2.toLong * isGood(i._1)).sum / 2)
}


import scala.io.StdIn

object Main {
  def test(): Unit = {
    val n = StdIn.readLine().toInt
    val ps : List[(Int, Int)] = (0 until n).flatMap {
      i => StdIn.readLine().toList.zipWithIndex.filter { _._1 == '*' }.map { x => (i, x._2) }
    }.toList

    var a = ps(0)._1
    var b = ps(1)._1
    var c = ps(0)._2
    var d = ps(1)._2

    if (a == b)
      b = (a + 1) % n
    if (c == d)
      d = (c + 1) % n

    for (i <- 0 to n - 1;
         j <- 0 to n) {
          if ((a == i || b == i)
            && (c == j || d == j))
            print("*")
          else {
            if (j == n)
              print("\n")
            else
              print(".")
          }
    }
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => test()
    }
  }
}

object cf1512 {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val n = readInt()
			var nLine = 0
			var x1 = 0
			var y1 = 0
			var x2 = 0
			var y2 = 0

			for (nLine <- 0 to n-1) {
				var line = Console.in.readLine()
				val x = line.indexOf('*')
				if (x > -1) {
					x1 = x2
					y1 = y2
					x2 = x
					y2 = nLine
					line = line.substring(x+1)
					val x3 = line.indexOf('*')
					if (x3 > -1) {
						x1 = x3+x2+1
						y1 = nLine
					}
				}
			}

			var minx = if (x1 < x2) x1 else x2
			var miny = if (y1 < y2) y1 else y2
			val width = if (x1 != x2) Math.abs(x1-x2) else 1
			val height = if (y1 != y2) Math.abs(y1-y2) else 1

			minx = if (x1 == x2 && (x1>= width)) x1-width else minx
			miny = if (y1 == y2 && (y1 >= height)) y1-height else miny

			for (nLine <- 0 to n-1) {
				var nCol = 0
				for (nCol <- 0 to n-1) {
					if ( (nLine == miny || nLine == miny+height) && (nCol == minx || nCol == minx+width) ) {
							print('*')
					} else {
						print('.')
					}
				}
				println()
			}

		}
	}
}

object cf1512 {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val n = readInt()
			var nLine = 0
			var x1 = 0
			var y1 = 0
			var x2 = 0
			var y2 = 0

			for (nLine <- 0 to n-1) {
				var line = Console.in.readLine()
				val x = line.indexOf('*')
				if (x > -1) {
					x1 = x2
					y1 = y2
					x2 = x
					y2 = nLine
					line = line.substring(x+1)
					val x3 = line.indexOf('*')
					if (x3 > -1) {
						x2 = x3+x1+1
						y2 = nLine
					}
				}
			}

			var minx = if (x1 < x2) x1 else x2
			var miny = if (y1 < y2) y1 else y2
			val width = if (x1 != x2) Math.abs(x1-x2) else 1
			val height = if (y1 != y2) Math.abs(y1-y2) else 1

			minx = if (x1 == x2 && (x1>= width)) x1-width else minx
			miny = if (y1 == y2 && (y1 >= height)) y1-height else miny

			for (nLine <- 0 to n-1) {
				var nCol = 0
				for (nCol <- 0 to n-1) {
					if ( (nLine == miny || nLine == miny+height) && (nCol == minx || nCol == minx+width) ) {
							print('*')
					} else {
						print('.')
					}
				}
				println()
			}

		}
	}
}


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

  override def apply(io: IO): io.type = {
    val good = (0 to (1<<10)).map(i => Integer.parseInt(i.toBinaryString, 3)).toArray
    repeat(io.read[Int]) {
      val n = io.read[Int]
      var idx = java.util.Arrays.binarySearch(good, n)
      if (idx < 0) idx = -idx - 1
      val ans = good(idx)
      io.writeLine(ans)
    }
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.StdIn

object Hello extends App {

  def solve(n: Long): Long = {
    val s = java.lang.Long.toString(n, 3)
    val goodNumber: String = s.indexOf('2') match {
      case -1 => s
      case pos2 => (pos2 - 1 to 0 by -1).find(i => s(i) == '0') match {
        case None => "1" + "0" * s.length
        case Some(pos0) =>
          val suffixLength = s.length - pos0 - 1
          s.substring(0, pos0) + "1" + ("0" * suffixLength)
      }
    }
    java.lang.Long.valueOf(goodNumber, 3)
  }

  val q = StdIn.readLine().toInt
  val queries = Iterator.continually(StdIn.readLine().toLong).take(q)
  queries.map(solve).foreach(println)
}

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    for (i <- 0 until q) {
      val n = io.read[Long]
      var power:Long = (1)
      while(power <= n) {
        power = power * 3
      }
      var ans = power
      var cur = power
      var value:Long = 0
      while(cur != 0) {
        var digit = (n / cur) % 3
        if(digit == 0) {
          if(value + cur >= n && value + cur < ans) ans = cur + value
        } else if(digit == 1) {
          value = value + cur
        } else {
          // do nothing
        }
        cur /= 3
      }
      if(value == n) {
        ans = n
      }
      io.writeLine(ans)
    }
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    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 _1249C1 extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    import java.lang.{Long => JLong}

    val good = (0 to (1<<9)).map(i => JLong.parseLong(i.toBinaryString, 3)).toArray
    debug(good.reverse.toList.take(10))

    repeat(io.read[Int]) {
      val n = io.read[Long]
      val base3 = "0" + java.lang.Long.toString(n, 3)

      val ans = if (base3.contains("2")) {
        val t = base3.indexOf("2")
        val z = base3.substring(0, t).lastIndexOf("0")
        val b3 = base3.substring(0, z) + "1" + ("0" * (base3.length - z - 1))
        JLong.parseLong(b3, 3)
      } else {
        n
      }
      io.writeLine(ans)
    }
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


import scala.collection.mutable.ArrayBuffer

object TheChildAndToy {
  case class Pair(u:Int,w:Int) extends Ordered[Pair]{
    override def compare(that: Pair): Int = {
      this.w compare that.w
    }
  }
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val weight=in.readLine().split(" ").map(_.toInt)
    val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt-1)
      graph(edge(0))+=edge(1)
      graph(edge(1))+=edge(0)
    }
    val rem=Array.ofDim[Int](n)
    //val pq=PriorityQueue[Pair]()
    for(i<- 0 until graph.length){
      var w=0
      for(j<- 0 until graph(i).length) {
        w+=weight(graph(i)(j))
      }
      rem(i)=w
      //pq.enqueue(Pair(i,w))
    }

    var sum=0
    for(i<- 0 until n){
      val u=getMin(rem,weight)
      sum+=rem(u)
      rem(u)= -1
      for(v<- 0 until graph(u).length){
        if(rem(graph(u)(v))!= -1){
          rem(graph(u)(v))-=weight(u)
        }
      }
    }
    println(sum)
  }
  def getMin(rem:Array[Int],weight:Array[Int]):Int={
    var max=Int.MinValue
    var minInd= -1
    for(i<- 0 until rem.length if(rem(i)!= -1)){
      if(weight(i)>max){
        max=weight(i)
        minInd=i
      }
    }
    return minInd
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println((1 to m).foldLeft(0) {
    case (acc, _) =>
      val Array(from, to) = in.next().split(' ').map(_.toInt - 1)
      acc + Math.min(data(from), data(to))
  })
}

object C437 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val vi = readInts(n).zipWithIndex.map {
      case (value, idx) =>
        (idx, value)
    }.toMap
    val orderToProcess =
      vi.toArray
        .sortBy {
          case (_, x) => -x
        }
        .map { _._1 }
    val graph = Array.fill(n)(cu.Set.empty[Int])
    for (_ <- 1 to m) {
      val Array(x, y) = readInts(2).map(_ - 1)
      graph(x).add(y)
      graph(y).add(x)
    }
    def remove(node: Int): Int = {
      var score = 0
      val nodes = graph(node)
      for (n <- nodes) {
        score += vi(n)
        graph(n).remove(node)
      }
      graph(node).clear()
      score
    }
    var res = 0
    for (node <- orderToProcess) {
      res += remove(node)
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}


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 X = nl()

    val a = X - 2
    val (i, j, k) = if (a % 3 == 0) {
      (1, 2, a - 1)
    } else {
      (1, 1, a)
    }

    out.println(s"$i $j $k")
  }

  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 CF511A extends App {

  import scala.io.StdIn

  val n = StdIn.readInt
  var (a, b, c) = (1, 1, n-2)

  if (c % 3 == 0) {
    c -= 1
    a += 1
  }

  println(a + " " + b + " " + c)
}

object Loves3 {
  def main(args: Array[String]): Unit = {
    val n=scala.io.StdIn.readInt()
    var i=0
    var j=0
    var k=0
    for(i <- 1 to n-2)
      for(j <- 1 to n-1-i){
          k=n-i-j
          if(i%3!=0 && j%3!=0 && k%3!=0){
              println(i+" "+j+" "+k)
              System.exit(0)
          }
      }
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){
        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 2) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    if(x == 0 && tt == 0){
      return (p+1) + " " + (p-2) + " " + (p+1)
    }
    return p + " " + p  + " " + p

  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){

        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 1) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    if(x == 0 && tt == 0){
      return (p+1) + " " + (p-2) + " " + (p+1)
    }
    return p + " " + p  + " " + p

  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val pp = n%3
    val t = p/3
    val tt = p%3
    val resFaltante = if (t > 0) tt else 4
    print(matches(resFaltante, p))
  }

  def matches(x:Int, p: Int): String = x match{
    case 0 => (p - 1) + " " + (p - 1 ) + " " + (p + 2)
    case 1 => p + " " + p  + " " + (p + 1)
    case 2 => p + " " + p  + " " + (p + 2)
    case 4 => p + " " + p  + " " + p
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val resFaltante = n%3
    print(matches(resFaltante, p))
  }

  def matches(x:Int, p: Int): String = x match{
    case 0 => p + " " + p  + " " + p
    case 1 => {
      if((p + 1)%3 != 0  )
        p + " " + p  + " " + (p + 1)
      else p + " " + (p + 2) + " " + (p - 1)
    }
    case 2 => {
      if((p + 2) % 3 != 0)
        p + " " + p  + " " + (p + 2)
      else p + " " + (p + 1)  + " " + (p + 1)
    }
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3
    print("residuo de tt:" + tt)

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){
        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 2) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    if(x == 0 && tt == 0){
      return (p+1) + " " + (p-2) + " " + (p+1)
    }
    return p + " " + p  + " " + p

  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){

        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 1) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    return p + " " + p  + " " + p
  }
}

object CF511A extends App {

  import scala.io.StdIn

  val n = StdIn.readInt
  var (a, b, c) = (n / 3, n / 3, n / 3 + n % 3)

  if (a%3 == 0) {
    a -= 1
    b += 1
  }
  if (b%3 == 0) {
    b -= 1
    c += 1
  }
  if (c%3 == 0) {
    c -= 1
    a += 1
  }

  println(a + " " + b + " " + c)
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  var oldNew = Map.empty[String, String]
  var newOne = Map.empty[String, String]
  (1 to t).foreach { _ =>
    val Array(old, new_) = in.next().split(" ")
    if (newOne.contains(old)) {
      val oldOld = newOne(old)
      oldNew += oldOld -> new_
      newOne += new_ -> oldOld
    } else {
      oldNew += old -> new_
      newOne += new_ -> old
    }
  }
  println(oldNew.size)
  println(oldNew.map(i => s"${i._1} ${i._2}").mkString("\n"))

}

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks
import scala.annotation.tailrec

object Problem extends App {
  import Scanner._

  val oldNames, allNames = mutable.HashSet[String]()
  val names = mutable.HashMap[String, String]()
  for(i <- 1 to readInt) {
    val (a, b) = (readString, readString)
    if(!allNames.contains(a)) {
      oldNames.add(a)
      allNames.add(a)
    }
    allNames.add(b)
    names.put(a, b)
  }

  def findName(name: String): String = names.get(name).map(findName(_)).getOrElse(name)

  println(oldNames.size)
  for(name <- oldNames)
    println(s"$name ${findName(name)}")
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = mutable.Map[A, B]()
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object B_Misha_and_Changing_Handles {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()

    val requests = for (i <- 1 to n) yield {
      (scanner.next(), scanner.next())
    }

    def processRequest (requests : List[(String, String)], acc: Map[String, Item] = Map()) : Map[String, Item] = {
      requests match {
        case (old_name, new_name) :: tail if acc contains old_name =>  {
          val old_item = acc(old_name)
          val new_item = new Item(old_item.initial, new_name)
          processRequest(tail, acc - old_name + (new_name -> new_item))
        }
        case (old_name, new_name) :: tail => {
          val new_item = new Item(old_name, new_name)
          processRequest(tail, acc + (new_name -> new_item))
        }
        case Nil => acc
      }
    }

    val map = processRequest(requests.toList)

    out.println(map.size)
    for (res <- map.toSeq.sortBy(x => x._2.initial)) {
      out.println(s"${res._2.initial} ${res._2.current}")
    }
  }

  case class Item(initial : String, current : String) {
  }
}

object Main extends App {
  val n = readInt
  val init = (Map[String, String](), Map[String, String]())
  val (mapping, _) = (1 to n).foldLeft(init)({
    case ((forward, backword), _) => {
      val Array(prev, next) = readLine.split(" ").filterNot(_ == "")
      backword.get(prev) match {
         case Some(name) =>
           (forward + (name -> next), backword + (next -> name))
         case None =>
           (forward + (prev -> next), backword + (next -> prev))
      }
    }
  })
  println(mapping.size)
  mapping foreach {
    case (from, to) => println(from + " " + to)
  }
}

object Main extends App {
  val n = readInt
  val init = (Map[String, String](), Map[String, String]())
  val (mapping, _) = (1 to n).foldLeft(init)({
    case ((forward, backword), _) => {
      val Array(prev, next) = readLine.split(" ").filterNot(_ == "")
      backword.get(prev) match {
         case Some(name) =>
           (forward + (name -> next), backword + (next -> name))
         case None =>
           (forward + (prev -> next), backword + (next -> prev))
      }
    }
  })
  mapping foreach {
    case (from, to) => println(from + " " + to)
  }
}


import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { m =>
      val n = readInt
      val arr = readLine.split(" ").map(_.toInt)
      val l = readLine.split(" ").map(_.toInt)
      val unlocked = (arr zip l).filter(x => x._2 == 0).map(_._1).sortBy(x => -x)
      var k = -1
      val result: Array[Int] = arr.zipWithIndex.map { case (e, i) =>
        if (l(i) == 0) {
          k += 1
          unlocked(k)
        } else {
          e
        }
      }
      println(result.mkString(" "))
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val ln = readLine().split(" ").map(_.toInt)

    val bn = (an zip ln).collect { case (a, 0) => a }.sorted
    val cn = (an zip ln)
      .foldRight((List.empty[Int], 0)) {
        case ((a, 1), (ck, i)) => (a :: ck, i)
        case ((_, 0), (ck, i)) => (bn(i) :: ck, i + 1)
      }
      ._1

    println(cn.mkString(" "))
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val ln = readLine().split(" ").map(_.toInt)

    val bn = (an zip ln).collect { case (a, 0) => a }.sorted(Ordering.Int.reverse)
    var i = -1
    val ans = (an zip ln).map {
      case (a, 0) => i += 1; bn(i)
      case (a, 1) => a
    }

    println(ans.mkString(" "))

  }
}


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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var list = List[(Int, Int)]();
    for (i <- 0 until n) {
      var Array(x, d) = readLine.split(" ").map(_.toInt)
      list = (x, d) :: list;
    }
    for (e <- list) {
      if (list.exists(p => p._1 == (e._1 + e._2) && e._1 == (p._1 + p._2))) {
        println("YES");
        return;
      }
    }
    println("NO");
  }

}

object P029A extends App {
  val n = readInt
  var pos    = (for (i <- 0 to n-1) yield 0) toArray
  var target = (for (i <- 0 to n-1) yield 0) toArray
  var lookup = collection.mutable.Map[Int, Int]()
  for (i <- 0 to n-1) {
    var elems = readLine.split(' ').map(x => x.toInt)
    pos(i)    = elems(0)
    target(i) = elems(0) + elems(1)
    lookup += ((pos(i), i))
  }
  println(if ((0 to n-1).exists(x => lookup.contains(target(x)) && lookup.get(target(lookup(target(x)))).getOrElse(null) == x)) "YES" else "NO")
}


object Main {

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int){
            if ( ts < t ){
                var Array(s1, s2) = io.StdIn.readLine().split(" ").map(_.reverse)
                if ( s1 == s2 )
                    println("=")
                else {
                    if ( s1 < s2 ){
                        if ( s1(0) != s2(0) || s1(0) == 'S' )
                            println(">")
                        else
                            println("<")
                    }
                    else {
                        if ( s1(0) != s2(0) || s1(0) == 'S' )
                            println("<")
                        else
                            println(">")
                    }
                }
                loopts(ts+1)
            }
        }

        loopts(0)
    }

}

object _1741A extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val a, b = io.nextStr()
    val ans = hash(a).compareTo(hash(b)) match {
      case 1 => ">"
      case -1 => "<"
      case _ => "="
    }
    io.printLine(ans)
  }

  def hash(s: String) = {
    val f = if (s.contains("M"))
      0
    else if (s.contains("S"))
      -1
    else
      1
   f*(1+s.count(_ == 'X'))
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextBool(): Boolean = nextInt() == 1
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}

object Main {

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int){
            if ( ts < t ){
                var Array(s1, s2) = io.StdIn.readLine().split(" ").map(_.reverse)
                if ( s1 == s2 )
                    println("=")
                else {
                    if ( s1 < s2 ){
                        if ( s1(0) == 'S' && s2(0) == 'S' )
                            println(">")
                        else
                            println("<")
                    }
                    else {
                        if ( s1(0) == 'L' && s2(0) == 'L' )
                            println(">")
                        else
                            println("<")
                    }
                }
                loopts(ts+1)
            }
        }

        loopts(0)
    }

}

object Main {

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int){
            if ( ts < t ){
                var Array(s1, s2) = io.StdIn.readLine().split(" ").map(_.reverse)
                if ( s1 == s2 )
                    println("=")
                else {
                    if ( s1 < s2 ){
                        if ( s1(0) == 'S' && s2(0) == 'S' )
                            println("<")
                        else
                            println(">")
                    }
                    else {
                        if ( s1(0) == 'L' && s2(0) == 'L' )
                            println(">")
                        else
                            println("<")
                    }
                }
                loopts(ts+1)
            }
        }

        loopts(0)
    }

}


object firstdemo extends  App {

  def readString() : String = {
    val yo = scala.io.StdIn.readLine()
    yo
  }
  def readInt() : Int = {
    val yo = scala.io.StdIn.readInt();
    yo
  }

     var t = readInt()

      while(t > 0) {

        val Array(x , y) = readString().split(" ")
        val n = x.toInt
        val k = y.toInt
       val list = readString().split(" ")
        val array = list.map(e => e.toInt)
        val yo = array.sortBy(e => e)
        var mx = 0
        for(e <- yo){
          mx = mx max e
        }
        val yy = yo(0) + yo(1)
      //  println(mx + " " + k + " " + yy)
        if(mx <= k || yy <= k)
          println("YES")
        else {
          println("NO")
        }
        t = t - 1

      }

}

object HelloWorld {
  def main(args: Array[String]) = {
    var t = scala.io.StdIn.readInt()
    while (t > 0) {
      val Array(n, d) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
      var min1 = 1e9
      var min2 = 1e9
      var A = scala.io.StdIn.readLine.split(" ").map(_.toInt)
      var ok = true
      for (i <- 0 until n) {
        var x = A(i)
        if (x <= min1) {
          min2 = min1
          min1 = x
        } else if (x <= min2) {
          min2 = x
        }
        if (x > d)
          ok = false
      }
      if (ok || min1 + min2 <= d)
        println("YES")
      else println("NO")
      t -= 1
    }
  }
}