You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$.

Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.

NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)
    var del = 0 until N - 1 indexWhere  { i =>
      S(i) > S(i + 1)
    }
    if (del == -1) del = N - 1

    rep(N) { i =>
      if (i != del) out.print(S(i))
    }
    out.println()
  }

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

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

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

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

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

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

import scala.collection.immutable.WrappedString
import scala.io.StdIn._

object MinimizeString extends App {
  val n = readInt()
  val string = readLine()

  println(minimize(string))

  def minimize(string: WrappedString): String = {

    def tailRecMinimize(string: Seq[Char], acc: Seq[Char]): Seq[Char] =
      string match {
        case firstSymbol +: secondSymbol +: tail =>
          if (secondSymbol < firstSymbol)
            acc.reverse ++ (secondSymbol +: tail)
          else tailRecMinimize(secondSymbol +: tail, firstSymbol +: acc)
        case _ => acc.reverse
      }

    tailRecMinimize(string, Nil).mkString
  }
}

import util.control.Breaks._

object ECR54 {
  def main(args:Array[String]) {
    val s = scala.io.StdIn.readLine().toInt
    val str = scala.io.StdIn.readLine()
    Q1(s, str)
  }
  def Q1(s : Int, str : String){
    var builder = new StringBuilder
    var changed = false
    breakable{
      for(i <- 0 until s - 1)
        if(str.charAt(i) > str.charAt(i + 1)){
          builder ++= str.substring(0, i)
          builder ++= str.substring(i + 1, str.length())
          changed = true
          break;
        }
    }
    if(!changed)
      builder ++= str.substring(0, str.length - 1)
    println(builder)
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)
    val first = Array.fill[Int](26)(-1)
    rep(N) { i =>
      val c = S(i) - 'a'
      if (first(c) == -1) first(c) = i
    }

    val c = first.lastIndexWhere(_ >= 0)
    rep(N) { i =>
      if (i != first(c)) out.print(S(i))
    }
    out.println()
  }

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

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

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

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

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

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


Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:  f(0) = 0;  f(2·x) = f(x);  f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(ai) = f(aj). Help him, count the number of such pairs.

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). The numbers in the lines are separated by single spaces.

In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample any pair (i, j) will do, so the answer is 3.In the second sample only pair (1, 2) will do.

import collection.mutable.Map
object B
{
    def main(args : Array[String])
    {
        val n = readInt
        val nums = readLine split(" ") map(_ toInt)
        val mp = Map[Int,Int]()
        val res = Map[Int,Int]()
        mp(0) = 0

        def f(v : Int) : Int =
        {
            if(mp.contains(v)) mp(v)
            else if(v%2==0) f(v/2)
            else f(v/2)+1
        }
        nums foreach
        {
            i =>
            val key = f(i)
            res(key) = res.getOrElse(key,0)+1
        }
        println((for((k,v) <- res) yield{v.toLong*(v-1)/2}) sum)
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    val c2=new Array[Long](n+1)
    for(i<-2 to n) c2(i)=c2(i-1)+i-1

    val fm=Map[Int,Int]()
    fm(0)=0

    def f(v:Int):Int={
        if(fm.contains(v)) return fm(v)
        if(v%2==0) f(v/2)
        else f(v/2)+1
    }

    val res=Map[Int,Int]()
    readLine.split(" ").map(_.toInt) foreach{i=>
        val key=f(i)
        res(key)=res.getOrElse(key, 0)+1
    }

    val ans=(for((k,v)<-res) yield{
        c2(v)
    }) sum

    println(ans)
}

object Main {

  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt.toBinaryString.count(_ == '1'))
    val map = scala.collection.mutable.Map[Int, Int]()
    for(e <- a) {
      val count = map.getOrElse(e, -1)
      map(e) = count + 1
    }
    println(map.values.map(i => i.toLong * (i.toLong + 1) / 2).sum)
  }
}

import collection.mutable.Map
object B
{
    def main(args : Array[String])
    {
        val n = readInt
        val nums = readLine split(" ") map(_ toInt)
        val mp = Map[Int,Int]()
        val res = Map[Int,Int]()
        mp(0) = 0

        def f(v : Int) : Int =
        {
            if(mp.contains(v)) mp(v)
            else if(v%2==0) f(v/2)
            else f(v/2)+1
        }
        nums foreach
        {
            i =>
            val key = f(i)
            res(key) = res.getOrElse(key,0)+1
        }
        println((for((k,v) <- res) yield{v*(v-1)/2}) sum)
    }
}

import collection.mutable.Map
object B
{
    def main(args : Array[String])
    {
        val n = readLine toInt
        val nums = readLine split(" ") map(_ toInt)
        val mp = Map[Long,Int]()
        mp(0) = 0

        def f(v : Int) : Int=
        {
            if(mp contains(v)) mp(v)
            else if(v%2==0) f(v/2)
            else f(v/2)+1
        }

        nums foreach
        {
            i =>
            val key = f(i)
            mp(key) = mp.getOrElse(key,0)+1
        }
        println((for((k,v) <- mp) yield{v*(v-1)/2}) sum)
    }
}

object Main {

  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt.toBinaryString.count(_ == '1'))
    val map = scala.collection.mutable.Map[Int, Int]()
    for(e <- a) {
      val count = map.getOrElse(e, -1)
      map(e) = count + 1
    }
    println(map.values.map(i => i * (i + 1) / 2).sum)
  }
}


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val res = (1 to n - 2).scanLeft(2) {
    case(acc, i) => (acc + i) % n + 1
  }
  println(res.mkString(" "))
}

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

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

  val N = sc.nextInt

  def solve(): List[Int] = {

    @tailrec
    def loop(acc: List[Int], i: Int): List[Int] = {
      if (i == N) acc.reverse.tail.map(_ + 1)
      else loop((acc.head + i) % N :: acc, i + 1)
    }

    loop(List(0), 1)
  }

  out.println(solve.mkString(" "))
  out.close
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val s = (2 until n).scanLeft(2) { (c, i) =>
      (c + i - 1) % n + 1
    }
    println(s.mkString(" "))
  }
}

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

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

  val N = sc.nextInt

  def solve(): List[Int] = {

    @tailrec
    def loop(acc: List[Int], i: Int): List[Int] = {
      if (i == N) acc.reverse.tail
      else loop((acc.head + i) % N :: acc, i + 1)
    }

    loop(List(1), 1)
  }

  out.println(solve.mkString(" "))
  out.close
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val s = (2 until n).scanLeft(2) { (c, i) =>
      (c + i) % n
    }
    println(s.mkString(" "))
  }
}


The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $$$(Ox)$$$ axis.On this street, there are $$$n$$$ antennas, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th antenna lies on the position $$$x_i$$$ and has an initial scope of $$$s_i$$$: it covers all integer positions inside the interval $$$[x_i - s_i; x_i + s_i]$$$.It is possible to increment the scope of any antenna by $$$1$$$, this operation costs $$$1$$$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want).To modernize the street, we need to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna. Note that it is authorized to cover positions outside $$$[1; m]$$$, even if it's not required.What is the minimum amount of coins needed to achieve this modernization?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 80$$$ and $$$n \le m \le 100\ 000$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$s_i$$$ ($$$1 \le x_i \le m$$$ and $$$0 \le s_i \le m$$$). On each position, there is at most one antenna (values $$$x_i$$$ are pairwise distinct).

You have to output a single integer: the minimum amount of coins required to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna.

NoteIn the first example, here is a possible strategy:  Increase the scope of the first antenna by $$$40$$$, so that it becomes $$$2 + 40 = 42$$$. This antenna will cover interval $$$[43 - 42; 43 + 42]$$$ which is $$$[1; 85]$$$  Increase the scope of the second antenna by $$$210$$$, so that it becomes $$$4 + 210 = 214$$$. This antenna will cover interval $$$[300 - 214; 300 + 214]$$$, which is $$$[86; 514]$$$  Increase the scope of the third antenna by $$$31$$$, so that it becomes $$$10 + 31 = 41$$$. This antenna will cover interval $$$[554 - 41; 554 + 41]$$$, which is $$$[513; 595]$$$ Total cost is $$$40 + 210 + 31 = 281$$$. We can prove that it's the minimum cost required to make all positions from $$$1$$$ to $$$595$$$ covered by at least one antenna.Note that positions $$$513$$$ and $$$514$$$ are in this solution covered by two different antennas, but it's not important.—In the second example, the first antenna already covers an interval $$$[0; 2]$$$ so we have nothing to do.Note that the only position that we needed to cover was position $$$1$$$; positions $$$0$$$ and $$$2$$$ are covered, but it's not important.

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

  case class Antenna(x: Int, s: Int)

  val n, m = nextInt
  val as = Array.fill(n) {
    val x, s = nextInt
    Antenna(x - 1, s)
  }.sortBy(_.x)

  val min = Array.fill(m)(Int.MaxValue / 2)

  for (i <- 0 until n) {
    val a = as(i)
    var add = 0
    while (add <= m) {
      val lPos = a.x - (if (add <= a.s) a.s else add)
      val leftMin = if (lPos > 0) min(lPos - 1) else 0
      val total = leftMin + (if (add > a.s) add - a.s else 0)
      val rPos = Math.min(m - 1, a.x + add)
      if (lPos >= 0 && total < min(lPos)) min(lPos) = total
      if (rPos < m && total < min(rPos)) {
        min(rPos) = total
      }
      add += 1
    }
    var aMin = Int.MaxValue / 2
    while (add >= 0) {
      val lPos = Math.max(0, a.x - add)
      val rPos = Math.min(m - 1, a.x + add)
      if (min(rPos) < aMin) aMin = min(rPos)
      if (aMin < min(lPos)) min(lPos) = aMin
      if (aMin < min(rPos)) min(rPos) = aMin
      add -= 1
    }
  }

  out.println(min.last)
  out.flush()

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

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

  case class Antenna(x: Int, s: Int)

  val n, m = nextInt
  val as = Array.fill(n) {
    val x, s = nextInt
    Antenna(x - 1, s)
  }.sortBy(_.x)

  val min = Array.fill(m)(Int.MaxValue / 2)

  for (i <- 0 until n) {
    val a = as(i)
    var add = 0
    var minMinLeft = Int.MaxValue / 2
    while (add <= a.s) {
      val leftPos = a.x - a.s
      val lPos = a.x - add
      val leftMin = if (leftPos > 0) min(leftPos - 1) else 0
      val leftMin2 = if (lPos > 0) min(lPos - 1) else 0
      if (leftMin < minMinLeft) minMinLeft = leftMin
      if (leftMin2 < minMinLeft) minMinLeft = leftMin2
      val total = minMinLeft
      val rPos = a.x + add
      if (lPos >= 0 && total < min(lPos)) min(lPos) = total
      if (rPos < m && total < min(rPos)) {
        min(rPos) = total
      }
      add += 1
    }
    while (add <= m) {
      val lPos = a.x - add
      val leftMin = if (lPos > 0) min(lPos - 1) else 0
      if (leftMin < minMinLeft) minMinLeft = leftMin
      val total = minMinLeft + (if (add > a.s) add - a.s else 0)
      val rPos = a.x + add
      if (lPos >= 0 && total < min(lPos)) min(lPos) = total
      if (rPos < m && total < min(rPos)) {
        min(rPos) = total
      }
      add += 1
    }
  }

  out.println(min.last)
  out.flush()

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

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

  case class Antenna(x: Int, s: Int)

  val n, m = nextInt
  val as = Array.fill(n) {
    val x, s = nextInt
    Antenna(x - 1, s)
  }.sortBy(_.x)

  val min = Array.fill(m)(Int.MaxValue / 2)

  for (i <- 0 until n) {
    val a = as(i)
    var add = 0
    var minMinLeft = Int.MaxValue / 2
    while (add <= a.s) {
      val leftPos = a.x - a.s
      val lPos = a.x - add
      val leftMin = if (leftPos > 0) min(leftPos - 1) else 0
      val leftMin2 = if (lPos > 0) min(lPos - 1) else 0
      if (leftMin < minMinLeft) minMinLeft = leftMin
      if (leftMin2 < minMinLeft) minMinLeft = leftMin2
      val total = minMinLeft
      val rPos = Math.min(m - 1, a.x + add)
      if (lPos >= 0 && total < min(lPos)) min(lPos) = total
      if (rPos < m && total < min(rPos)) {
        min(rPos) = total
      }
      add += 1
    }
    while (add <= m) {
      val lPos = a.x - add
      val leftMin = if (lPos > 0) min(lPos - 1) else 0
      if (leftMin < minMinLeft) minMinLeft = leftMin
      val total = minMinLeft + (if (add > a.s) add - a.s else 0)
      val rPos = Math.min(m - 1, a.x + add)
      if (lPos >= 0 && total < min(lPos)) min(lPos) = total
      if (rPos < m && total < min(rPos)) {
        min(rPos) = total
      }
      add += 1
    }
  }

  out.println(min.last)
  out.flush()

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


They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?

The first line of the input contains two integers h and w (1 ≤ h, w ≤ 500) – the number of rows and the number of columns, respectively. The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#' — denoting an empty or forbidden cell, respectively. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries. Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1 ≤ r1i ≤ r2i ≤ h, 1 ≤ c1i ≤ c2i ≤ w) — the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.

Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.

NoteA red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(h, w) = in.next().split(' ').map(_.toInt)
  val data = (1 to h).map(_ => in.next())
  val hor = Array.ofDim[Int](h + 1, w + 1)
  val ver = Array.ofDim[Int](h + 1, w + 1)
  data.indices.foreach { r =>
    var hooor = 0
    (0 until w).foreach { c =>
      if (data(r)(c) == '.' && c > 0 && data(r)(c - 1) == '.')
        hooor = hooor + 1
      hor(r + 1)(c + 1) = hor(r)(c + 1) + hooor

    }
  }
  (0 until w).foreach { c =>
    var veeer = 0
    data.indices.foreach { r =>
      if (data(r)(c) == '.' && r > 0 && data(r - 1)(c) == '.')
        veeer = veeer + 1
      ver(r + 1)(c + 1) = ver(r + 1)(c) + veeer
    }
  }

  val q = in.next().toInt
  println((1 to q).map { _ =>
    val Array(r1, c1, r2, c2) = in.next().split(' ').map(_.toInt)
    //6
//    r[r2][c2]-r[r2][c1]-r[r1-1][c2]+r[r1-1][c1]
    val horV = hor(r2)(c2) - hor(r2)(c1) - hor(r1 - 1)(c2)  + hor(r1 - 1)(c1)
//    c[r2][c2]-c[r1][c2]-c[r2][c1-1]+c[r1][c1-1]
    val verV = ver(r2)(c2) - ver(r1)(c2) - ver(r2)(c1 - 1) + ver(r1)(c1 - 1)
    horV + verV
  }.mkString("\n"))
}

import scala.util.Try

object C611 {
  @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(h, w) = readInts(2)
    val input = new Array[String](h)
    for(i <- 0 until h) {
      input(i) = scala.io.StdIn.readLine
    }
    val hor = Array.ofDim[Long](h+1, w+1)
    val ver = Array.ofDim[Long](h+1, w+1)
    for(i <- 0 to h) {
      for(j <- 0 to w) {
        if(i == 0 || j == 0) {
          ver(i)(j) = 0
          hor(i)(j) = 0
        } else {
          ver(i)(j) = ver(i-1)(j) + ver(i)(j-1) - ver(i-1)(j-1)
          hor(i)(j) = hor(i-1)(j) + hor(i)(j-1) - hor(i-1)(j-1)
          if(i < h && input(i-1)(j-1) == '.' && input(i)(j-1) == '.'){
            ver(i)(j) += 1
          }
          if(j < w && input(i-1)(j-1) == '.' && input(i-1)(j) == '.'){
            hor(i)(j) += 1
          }
        }
      }
    }

    def answer(r1: Int, c1: Int, r2: Int, c2: Int): Long = {
      hor(r2)(c2-1) - hor(r1-1)(c2-1) - hor(r2)(c1-1) + hor(r1-1)(c1-1) +
      ver(r2-1)(c2) - ver(r2-1)(c1-1) - ver(r1-1)(c2) + ver(r1-1)(c1-1)
    }

    val Array(q) = readInts(1)
    for(_ <- 0 until q) {
      val Array(r1, c1 ,r2, c2) = readInts(4)
      println(answer(r1, c1, r2, c2))
    }
  }
}

import scala.collection._

object C extends App {

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

  val Array(h, w) = readInts(2)
  val g = Array.fill(h)(readLine.toCharArray.map(_ == '.'))

  val cnt = Array.fill(h, w){ 0 }

  @inline def get(r: Int, c: Int): Int = {
    if (r < 0 || c < 0) 0 else cnt(r)(c)
  }

  @inline def count(r1: Int, c1: Int, r2: Int, c2: Int): Int = {
    var sum = 0
    if (c1 > 0) {
      var r = r1
      while (r <= r2) {
        if (g(r)(c1 - 1) && g(r)(c1)) sum += 1
        r += 1
      }
    }
    if (r1 > 0) {
      var c = c1
      while (c <= c2) {
        if (g(r1 - 1)(c) && g(r1)(c)) sum += 1
        c += 1
      }
    }
    sum
  }

  for (r <- 0 until h) {
    for (c <- 0 until w) {
      cnt(r)(c) = get(r - 1, c) + get(r, c - 1) - get(r - 1, c - 1) + count(r, c, r, c)
    }
  }

  val Array(q) = readInts(1)

  val res = Array.ofDim[Int](q)

  for (i <- 0 until q) {
    val Array(r1, c1, r2, c2) = readInts(4).map(_ - 1)
    res(i) = get(r2, c2) - get(r2, c1 - 1) - get(r1 - 1, c2) + get(r1 - 1, c1 - 1) - count(r1, c1, r2, c2)
  }

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

  println(res.mkString("\n"))

  Console.flush
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(h, w) = readLine().split(" ").map(_.toInt)

    val gb = mutable.ArrayBuilder.make[String]()

    (0 until h).foreach( _ => gb += readLine() )

    val grid = gb.result()

    val p = Array.fill(h, w)(0)
    val r = Array.fill(h, w)(0)
    val c = Array.fill(w, h)(0)

    for (i <- 0 until h) {
      for (j <- 0 until w) {
        var extra = 0
        for (k <- 0 to i) {
          if (j > 0 && grid(k)(j-1) == '.' && grid(k)(j) == '.') extra += 1
        }
        for (k <- 0 until i) {
          if (grid(k)(j) == '.' && grid(k+1)(j) == '.') extra += 1
        }
        p(i)(j) = if (j > 0) p(i)(j-1) + extra else extra

        if (j > 0) r(i)(j) = r(i)(j-1) + (if(grid(i)(j-1) == '.' && grid(i)(j) == '.') 1 else 0)

        if (i > 0) c(j)(i) = c(j)(i-1) + (if(grid(i-1)(j) == '.' && grid(i)(j) == '.') 1 else 0)
      }
    }

//    for (i <- 0 until h) {
//      for (j <- 0 until w) {
//        print(p(i)(j) + " ")
//      }
//      print("\n")
//    }

    val sb = mutable.StringBuilder.newBuilder

    (0 until readLine().toInt).foreach { _ =>
      val Array(r1, c1, r2, c2) = readLine().split(" ").map(_.toInt-1)

      val joint = r(r1)(c2) - r(r1)(c1) + c(c1)(r2) - c(c1)(r1)

      val res = p(r2)(c2) - p(r1)(c2) - p(r2)(c1) + p(r1)(c1) + joint
      sb.append(res + "\n")
    }

    print(sb)
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val h = sc.nextInt()
    val w = sc.nextInt()
    sc.nextLine()

    val grid = new Array[String](h)
    for(i <- 0 until h)
      grid(i) = sc.nextLine()

    val q = sc.nextInt()
    sc.nextLine()

    /// dp
    // var dpy = new Array[Int](h+1)
    // var dpx = new Array[Int](w+1)
    var dpy = Array.ofDim[Int](h+1, w+1)
    var dpx = Array.ofDim[Int](h+1, w+1)

    // dpx
    for(y <- 1 to h){
      val s = grid(y-1)
      var stock = '#'
      for(x <- 1 to w){
        var now = s(x-1)

        dpx(y)(x) = dpx(y)(x-1)
        if(now == '.' && stock == '.')
          dpx(y)(x) += 1

        stock = now
      }
    }
    // dpy
    for(x <- 1 to w){
      var stock = '#'
      for(y <- 1 to h){
        var now = grid(y-1)(x-1)

        dpy(y)(x) = dpy(y-1)(x)
        if(now == '.' && stock == '.')
          dpy(y)(x) += 1

        stock = now
      }
    }

    // for(i <- 1 to h){
    //   for(j <- 1 to w){
    //     print(dpy(i)(j))
    //   }
    //   println()
    // }

    for(k <- 1 to q){
      val y1 = sc.nextInt()
      val x1 = sc.nextInt()
      val y2 = sc.nextInt()
      val x2 = sc.nextInt()

      var ans = 0

      for(i <- x1 to x2)
        ans += dpy(y2)(i) - dpy(y1)(i)
      for(i <- y1 to y2)
        ans += dpx(i)(x2) - dpx(i)(x1)

      println(ans)
    }
  }
}


Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. There are $$$n$$$ cities and $$$n-1$$$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $$$1$$$ to $$$n$$$, and the city $$$1$$$ is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly $$$k$$$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose $$$k$$$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2\le n\le 2 \cdot 10^5$$$, $$$1\le k< n$$$)  — the number of cities and industry cities respectively. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is a road connecting city $$$u$$$ and city $$$v$$$. It is guaranteed that from any city, you can reach any other city by the roads.

Print the only line containing a single integer  — the maximum possible sum of happinesses of all envoys.

NoteIn the first example, Linova can choose cities $$$2$$$, $$$5$$$, $$$6$$$, $$$7$$$ to develop industry, then the happiness of the envoy from city $$$2$$$ is $$$1$$$, the happiness of envoys from cities $$$5$$$, $$$6$$$, $$$7$$$ is $$$2$$$. The sum of happinesses is $$$7$$$, and it can be proved to be the maximum one.In the second example, choosing cities $$$3$$$, $$$4$$$ developing industry can reach a sum of $$$3$$$, but remember that Linova plans to choose exactly $$$k$$$ cities developing industry, then the maximum sum is $$$2$$$.

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

object Solution_C extends App {

  type Graph = Array[mutable.MutableList[Int]]
  val Array(n, k) = StdIn.readLine().split(' ').map{_.toInt}
  val graph = Array.fill[mutable.MutableList[Int]](n + 1)(mutable.MutableList())
  for (e <- 1 until n) {
    val Array(from, to) = StdIn.readLine().split(' ').map{_.toInt}
    graph(from) += to
    graph(to) += from
  }
  val visited = Array.ofDim[Int](n + 1)
  val distance = Array.ofDim[Int](n + 1)
  val parent = Array.ofDim[Int](n + 1)
  val subtreeSize = Array.ofDim[Int](n + 1)
  val stack = mutable.Stack[(Int, mutable.MutableList[Int])]()
  parent(1) = 1
  stack.push((1, graph(1)))
  visited(1) = 1
  while (stack.nonEmpty) {
    val (root, edges) = stack.top
    var black = true
    var tmp = edges
    while (black && tmp.nonEmpty) {
      val to = tmp.head
      tmp = tmp.tail
      if (visited(to) == 0) {
        visited(to) = 1
        distance(to) = distance(root) + 1
        parent(to) = root
        stack.pop()
        stack.push((root, tmp))
        stack.push((to, graph(to)))
        black = false
      }
    }
    if (black) {
      var sum = 0
      graph(root) foreach { to =>
        if (parent(root) != to) {
          sum += subtreeSize(to) + 1
        }
      }
      subtreeSize(root) = sum
      stack.pop()
    }
  }

  for (i <- 0 to n) {
    subtreeSize(i) = distance(i) - subtreeSize(i)
  }
  var res = 0L
  val sorted = subtreeSize.slice(1, n + 1).sortWith(_ > _)
  for (i <- 0 until k) {
    res += sorted(i)
  }
  println(res)
}


The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.

Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).

NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".

object Main {
    def main(args: Array[String]){
      val n = readLine().toInt
      val nums: Array[String] = readLine().split(' ')

      var minIndex = 0
      var minCount = 0
      var min = Integer.MAX_VALUE

      for (val i <- 0.to(n-1)){
        val number = nums(i) .toInt
        if (number < min){
          minIndex = i
          minCount = 0
          min = number
        } else if (number == min){
          minCount += 1
        }
      }

      if (minCount == 0){
        println(minIndex + 1)
      } else {
        println("Still Rozdil")
      }
    }
}

// very bad
object Main extends App {
  val lengthOfList = readLine.toLong
  val list = readLine.split(" ").map(_.toLong)
  var count = 0
  var min = 0
  for (x <- 1 to list.size - 1) {
    if (list(x) < list(min)) {
      min = x
      count = 0
    } else if (list(x) == list(min)) {
      count = count + 1
    }
  }

  if (count != 0) {
    println("Still Rozdil")
  } else {
    println(min + 1)
  }
}

object Main extends App {
  val length = readLine().toInt
  val xs = readLine().split(" ").map(_.toInt)
  val min = xs.min
  if (xs.count(_ == min) > 1) println("Still Rozdil")
  else println(xs.indexOf(min) + 1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val sort = data.sorted
  if (sort.length > 1 && sort(0) == sort(1))
    println("Still Rozdil")
  else
    println(data.indices.find(i => data(i) == sort.head).get + 1)

}

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

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

  val N = sc.nextInt
  val D = List.fill(N)(sc.nextInt)

  def solve(): Any = {
    D.zipWithIndex.sortWith(_._1 < _._1) match {
      case (x, y) :: Nil                           => y + 1
      case (x0, y0) :: (x1, y1) :: rest if x0 < x1 => y0 + 1
      case _ => "Still Rozdil"
    }
  }

  out.println(solve)
  out.close
}

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)

  val n = readInt
  val d = readInts
  val mindist = d.min
  val nearest = (d zip (1 to n)).filter(_._1 == mindist).map(_._2)
  val ans = if (nearest.size == 1) nearest.head else "Still Rozdil"

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

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val min = a.min
    val all = a.zipWithIndex.filter(t => t._1 == min)
    if (all.size > 1) println("Still Rozdil")
    else println(all(0)._2 + 1)
  }
}

// very bad
object Main extends App {
  val lengthOfList = readLine.toLong
  val list = readLine.split(" ").map(_.toLong)
  var count = 0
  var min = 0
  for (x <- 1 to list.size - 1) {
    if (list(x) < list(min)) {
      min = x
      count = 0
    } else if (list(x) == list(min)) {
      count = count + 1
    }
  }

  if (count != 0) {
    println("Still Razdil")
  } else {
    println(min + 1)
  }
}

// very bad
object Main extends App {
  val lengthOfList = readLine.toLong
  val list = readLine.split(" ").map(_.toLong)
  var count = 0
  var min = 0
  for (x <- list.indices) {
    if (list(x) < list(min)) {
      min = x
      count = 0
    }
    if (list(x) == min) {
      count = count + 1
    }
  }

  if (count != 0) {
    println("Still Razdol")
  } else {
    println(min + 1)
  }
}

// very bad
object Main extends App {
  val lengthOfList = readLine.toLong
  val list = readLine.split(" ").map(_.toLong)
  var count = 0
  var min = 0
  for (x <- 1 to list.size - 1) {
    if (list(x) < list(min)) {
      min = x
      count = 0
    }
    if (list(x) == list(min)) {
      count = count + 1
    }
  }

  if (count != 0) {
    println("Still Razdil")
  } else {
    println(min + 1)
  }
}

object Main extends Application {
  println("Still Razdol")
}

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

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

  val N = sc.nextInt
  val D = List.fill(N)(sc.nextInt)

  def solve(): Any = {
    D.zipWithIndex.sortWith(_._1 < _._1) match {
      case (x0, y0) :: (x1, y1) :: rest if x0 < x1 => y0 + 1
      case _ => "Still Rozdil"
    }
  }

  out.println(solve)
  out.close
}


Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $$$n$$$.Madoka is too tired of math to solve it herself, so help her to solve this problem!

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the required sum of the digits.

For each test case print the maximum number you can obtain.

NoteThe only numbers with the sum of digits equal to $$$2$$$ without zeros are $$$2$$$ and $$$11$$$. But the last one has two ones in a row, so it's not valid. That's why the answer is $$$2$$$.The only numbers with the sum of digits equal to $$$3$$$ without zeros are $$$111$$$, $$$12$$$, $$$21$$$, and $$$3$$$. The first one has $$$2$$$ ones in a row, so it's not valid. So the maximum valid number is $$$21$$$.The only numbers with the sum of digits equals to $$$4$$$ without zeros are $$$1111$$$, $$$211$$$, $$$121$$$, $$$112$$$, $$$13$$$, $$$31$$$, $$$22$$$, and $$$4$$$. Numbers $$$1111$$$, $$$211$$$, $$$112$$$, $$$22$$$ aren't valid, because they have some identical digits in a row. So the maximum valid number is $$$121$$$.

import scala.io.StdIn.readLine

object Solution {
  def solve() = {
    val i = readLine().toInt
    val r = i % 3
    if (r == 0) {
      val len = i * 2 / 3
      (for (

        j <- 0 until len;
        res = if (j % 2 == 0) 2 else 1
      ) yield res) mkString ("")

    }
    else if (r == 1) {
      val len = 1 + i * 2 / 3
      (for (

        j <- 0 until len;
        res = if (j % 2 == 0) 1 else 2
      ) yield res) mkString ("")
    }
    else {
      val len = i * 2 / 3
      (for (
        j <- 0 until len;
        res = if (j % 2 == 0) 2 else 1
     )yield res) mkString ("");

    }

  }

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

    val cases = readLine().toInt
    for (
      i <- 0 until cases
    ) println(solve())

  }
}


You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.$$$n$$$ reviewers enter the site one by one. Each reviewer is one of the following types:   type $$$1$$$: a reviewer has watched the movie, and they like it — they press the upvote button;  type $$$2$$$: a reviewer has watched the movie, and they dislike it — they press the downvote button;  type $$$3$$$: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once.Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of reviewers. The second line of each testcase contains $$$n$$$ integers $$$r_1, r_2, \dots, r_n$$$ ($$$1 \le r_i \le 3$$$) — the types of the reviewers in the same order they enter the site.

For each testcase print a single integer — the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to.

NoteIn the first testcase of the example you can send the only reviewer to either of the servers — they'll downvote anyway. The movie won't receive any upvotes.In the second testcase of the example you can send all reviewers to the first server:   the first reviewer upvotes;  the second reviewer downvotes;  the last reviewer sees that the number of downvotes is not greater than the number of upvotes — upvote themselves. There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer — to the second server:   the first reviewer upvotes on the first server;  the second reviewer downvotes on the first server;  the last reviewer sees no upvotes or downvotes on the second server — upvote themselves.

object Main {

  // @formatter:off
  private object r {
    import java.io._
    import java.util._
    val reader = new BufferedReader(new InputStreamReader(java.lang.System.in))
    var tok = new StringTokenizer("")

    def ln(): String =  {
      while (!tok.hasMoreElements) tok = new StringTokenizer(reader.readLine())
      tok.nextToken("\n")
    }
    def int(): Int = ln().toInt
    def long(): Long = ln().toLong
    def strs(): Array[String] = ln().split(' ')
    def ints(): Array[Int] = strs().map(_.toInt)
    def longs(): Array[Long] = strs().map(_.toLong)
  }
  // @formatter:on

  def run(): Unit = {
    val (n, v) = (r.int(), r.ints())
    println(v.count(it => it == 1 || it == 3))
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to r.int()) run()
  }
}

object Main {

  // @formatter:off
  private object r {
    def ln(): String = scala.io.StdIn.readLine()
    def int(): Int = ln().toInt
    def long(): Long = ln().toLong
    def ints(): Array[Int] = ln().split(' ').map(_.toInt)
    def longs(): Array[Long] = ln().split(' ').map(_.toLong)
  }
  private val o = new scala.collection.mutable.ListBuffer[Any]
  // @formatter:on

  def run(): Unit = {
    val (n, v) = (r.int(), r.ints())
    o += v.count(it => it == 1 || it == 3)
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to r.int()) run()
    if (o.nonEmpty) println(o.mkString("\n"))
  }
}

object Main {
  // @formatter:off
  private object read {
    def ln(): String = scala.io.StdIn.readLine()
    def int(): Int = ln().toInt
    def long(): Long = ln().toLong
    def ints(): Array[Int] = ln().split(' ').map(_.toInt)
    def longs(): Array[Long] = ln().split(' ').map(_.toLong)
  }
  // @formatter:on

  def run(): Unit = {
    val (n, v) = (read.int(), read.ints())
    println(v.count(it => it == 1 || it == 3))
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to readInt()) run()
  }
}


$$$n$$$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $$$i$$$-th robot is currently located at the point having coordinates ($$$x_i$$$, $$$y_i$$$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $$$X$$$ and $$$Y$$$, and when each robot receives this command, it starts moving towards the point having coordinates ($$$X$$$, $$$Y$$$). The robot stops its movement in two cases:  either it reaches ($$$X$$$, $$$Y$$$);  or it cannot get any closer to ($$$X$$$, $$$Y$$$). Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($$$x_c$$$, $$$y_c$$$). Then the movement system allows it to move to any of the four adjacent points:  the first action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c - 1$$$, $$$y_c$$$);  the second action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c$$$, $$$y_c + 1$$$);  the third action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c + 1$$$, $$$y_c$$$);  the fourth action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c$$$, $$$y_c - 1$$$). Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $$$X$$$ and $$$Y$$$ so that each robot can reach the point ($$$X$$$, $$$Y$$$). Is it possible to find such a point?

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. Each query begins with one line containing one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of robots in the query. Then $$$n$$$ lines follow, the $$$i$$$-th of these lines describes the $$$i$$$-th robot in the current query: it contains six integer numbers $$$x_i$$$, $$$y_i$$$, $$$f_{i, 1}$$$, $$$f_{i, 2}$$$, $$$f_{i, 3}$$$ and $$$f_{i, 4}$$$ ($$$-10^5 \le x_i, y_i \le 10^5$$$, $$$0 \le f_{i, j} \le 1$$$). The first two numbers describe the initial location of the $$$i$$$-th robot, and the following four numbers describe which actions the $$$i$$$-th robot can use to move ($$$f_{i, j} = 1$$$ if the $$$i$$$-th robot can use the $$$j$$$-th action, and $$$f_{i, j} = 0$$$ if it cannot use the $$$j$$$-th action). It is guaranteed that the total number of robots over all queries does not exceed $$$10^5$$$.

You should answer each query independently, in the order these queries appear in the input. To answer a query, you should do one of the following:   if it is impossible to find a point that is reachable by all $$$n$$$ robots, print one number $$$0$$$ on a separate line;  if it is possible to find a point that is reachable by all $$$n$$$ robots, print three space-separated integers on the same line: $$$1$$$ $$$X$$$ $$$Y$$$, where $$$X$$$ and $$$Y$$$ are the coordinates of the point reachable by all $$$n$$$ robots. Both $$$X$$$ and $$$Y$$$ should not exceed $$$10^5$$$ by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding $$$10^5$$$ by absolute value.

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

  override def apply(io: IO): io.type = {
    val inputs = io.read[Seq[Seq[((Int, Int), (Boolean, Boolean, Boolean, Boolean))]]]
    val inf = 1e5.toInt

    inputs foreach {robots =>
      var maxX, maxY = inf
      var minX, minY = -inf
      robots foreach {case ((x, y), (l, u, r, d)) =>
        if (!l) minX = minX max x
        if (!r) maxX = maxX min x
        if (!u) maxY = maxY min y
        if (!d) minY = minY max y
      }
      if (minX <= maxX && minY <= maxY) {
        io.writeAll(Seq(1, (minX + maxX)/2, (minY + maxY)/2)).writeLine()
      } else {
        io.writeLine(0)
      }
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[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 Main {
  import java.io._
  import java.util.StringTokenizer
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import Math._

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

  def main (args: Array[String]){

    val q = in.next().toInt
    for (_ <- 1 to q) {
      val n = in.next().toInt

      val m = 100000
      var xl = -m
      var xr = m
      var yu = -m
      var yd = m

      breakable {
        for(_ <- 1 to n) {
          val x, y, f1, f2, f3, f4 = in.next().toInt
          if (f1 == 0) {
            xl = max(xl, x)
          }
          if (f2 == 0) {
            yd = min(yd, y)
          }
          if (f3 == 0) {
            xr = min(xr, x)
          }
          if (f4 == 0) {
            yu = max(yu, y)
          }

          // pw.println(xl, xr, yu, yd)
        }
      }

      if(xl <= xr && yu <= yd) {
        pw.println(s"1 $xl $yu")
      }
      else {
        pw.println(0)
      }
    }

    pw.flush()
  }
}

import java.io._
import java.util.StringTokenizer
class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

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

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

  def main (args: Array[String]){

    val q = in.next().toInt
    for (_ <- 1 to q) {
      val n = in.next().toInt

      var flag = true
      val m = 100000
      var xl = -m
      var xr = m
      var yu = -m
      var yd = m

      breakable {
        for(_ <- 1 to n) {
          val x, y, f1, f2, f3, f4 = in.next().toInt
          if (f1 == 0) {
            if (x > xr) {
              flag = false
              break
            }
            else
              xl = max(xl, x)
          }
          if (f2 == 0) {
            if (y < yu) {
              flag = false
              break
            }
            else
              yd = min(yd, y)
          }
          if (f3 == 0) {
            if (x < xl) {
              flag = false
              break
            }
            else
              xr = min(xr, x)
          }
          if (f4 == 0) {
            if (y > yd) {
              flag = false
              break
            }
            else
              yu = max(yu, y)
          }

          // pw.println(xl, xr, yu, yd)
        }
      }

      if(flag && xl <= xr && yu <= yd) {
        pw.println(s"1 $xl $yu")
      }
      else {
        pw.println(0)
      }
    }

    pw.flush()
  }
}

import java.io._
import java.util.StringTokenizer
class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.

The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).

If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Notegcd(x, y) is greatest common divisor of x and y.

object A extends App{
    val Array(n,k) = readLine.split(' ').map(_.toInt)
    if(k < (n/2)) println(-1) else if (n == 1)  println(if( k > 0) -1 else 1) else {
        val d = k-(n/2) + 1
        val nums = d::(2*d)::Iterator.from(2*d+1).filter(_ != d).filter(_ != 2*d).take(n-2).toList
        println(nums.mkString(" "))
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toLong)
  if (k < n / 2 || (n == 1 && k > 0))
    println(-1)
  else if (n == 1)
    println(1)
  else {
    var i = 1
    val left = k - n / 2 + 1
    val r = (1l to ((n + 1) / 2)).flatMap { z =>
      if (z == 1) {
        List(left, left * 2)
      }
      else if (z == (n + 1) / 2 && n % 2 == 1) {
        if (i == left || i == left * 2)
          i += 1
        List(i)
      }
      else {
        while (i == left || i == left * 2 || (i + 1) == left || (i + 1) == left * 2)
          i += 2
        i += 2
        List(i - 2, i - 1)
      }
    }
    println(r.mkString(" "))
  }
}

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

object A extends App {

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

  val Array(n, k) = readInts(2)
  val MAX = 1000000000
  val as = new mutable.ArrayBuffer[Long](n.toInt)

  if (n / 2 > k || (n == 1 && k > 0)) {
    println(-1)
  } else {
    var start = 1
    if (n < k * 2) {
      val need = (k - n / 2 + 1)
      val a = (MAX / need) * need
      val b = a - need
      as += a
      as += b
      start = 3
    }
    for (i <- start to n) as += i

    println(as.mkString(" "))
  }
}

object A extends App{
    val Array(n,k) = readLine.split(' ').map(_.toInt)
    if(k < (n/2)) println(-1) else {
        val d = k-(n/2) + 1
        val nums = d::(2*d)::Iterator.from(2*d+1).filter(_ != d).filter(_ != 2*d).take(n-2).toList
        println(nums.mkString(" "))
    }
}

object A extends App{
    val Array(n,k) = readLine.split(' ').map(_.toInt)
    if(k < (n/2)) println(-1) else if (n == 1 && k > 0){
        val d = k-(n/2) + 1
        val nums = d::(2*d)::Iterator.from(2*d+1).filter(_ != d).filter(_ != 2*d).take(n-2).toList
        println(nums.mkString(" "))
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toLong)
  if (k < n / 2)
    println(-1)
  else {
    var i = 1
    val left = k - n / 2 + 1
    val r = (1l to ((n + 1) / 2)).flatMap { z =>
      if (z == 1) {
        List(left, left * 2)
      }
      else if (z == (n + 1) / 2 && n % 2 == 1) {
        if (i == left || i == left * 2)
          i += 1
        List(i)
      }
      else {
        while (i == left || i == left * 2 || (i + 1) == left || (i + 1) == left * 2)
          i += 2
        i += 2
        List(i - 2, i - 1)
      }
    }
    println(r.mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toLong)
  if (k < n / 2)
    println(-1)
  else {
    var i = 1
    val left = k - n / 2 + 1
    val r = (1l to ((n + 1) / 2)).flatMap { z =>
      if (z == 1) {
        List(left, left * 2)
      }
      else if (z == (n + 1) / 2 && n % 2 == 1) {
        if (i == left || i == left * 2)
          i += 1
        List(i)
      }
      else {
        if (i == left || i == left * 2 || (i + 1) == left || (i + 1) == left * 2)
          i += 2
        i += 2
        List(i - 2, i - 1)
      }
    }
    println(r.mkString(" "))
  }
}

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

object A extends App {

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

  val Array(n, k) = readInts(2)
  val MAX = 1000000000
  val as = new mutable.ArrayBuffer[Long](n.toInt)

  if (n / 2 > k || (n == 1 && k > 0)) {
    println(-1)
  } else {
    var start = 1
    if (n < k * 2) {
      as += MAX
      as += (MAX - (k - n / 2 + 1))
      start = 3
    }
    for (i <- start to n) as += i

    println(as.mkString(" "))
  }
}


Suppose there is a $$$h \times w$$$ grid consisting of empty or full cells. Let's make some definitions:  $$$r_{i}$$$ is the number of consecutive full cells connected to the left side in the $$$i$$$-th row ($$$1 \le i \le h$$$). In particular, $$$r_i=0$$$ if the leftmost cell of the $$$i$$$-th row is empty.  $$$c_{j}$$$ is the number of consecutive full cells connected to the top end in the $$$j$$$-th column ($$$1 \le j \le w$$$). In particular, $$$c_j=0$$$ if the topmost cell of the $$$j$$$-th column is empty. In other words, the $$$i$$$-th row starts exactly with $$$r_i$$$ full cells. Similarly, the $$$j$$$-th column starts exactly with $$$c_j$$$ full cells.    These are the $$$r$$$ and $$$c$$$ values of some $$$3 \times 4$$$ grid. Black cells are full and white cells are empty. You have values of $$$r$$$ and $$$c$$$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $$$r$$$ and $$$c$$$. Since the answer can be very large, find the answer modulo $$$1000000007\,(10^{9} + 7)$$$. In other words, find the remainder after division of the answer by $$$1000000007\,(10^{9} + 7)$$$.

The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \le h, w \le 10^{3}$$$) — the height and width of the grid. The second line contains $$$h$$$ integers $$$r_{1}, r_{2}, \ldots, r_{h}$$$ ($$$0 \le r_{i} \le w$$$) — the values of $$$r$$$. The third line contains $$$w$$$ integers $$$c_{1}, c_{2}, \ldots, c_{w}$$$ ($$$0 \le c_{j} \le h$$$) — the values of $$$c$$$.

NoteIn the first example, this is the other possible case.  In the second example, it's impossible to make a grid to satisfy such $$$r$$$, $$$c$$$ values.In the third example, make sure to print answer modulo $$$(10^9 + 7)$$$.

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

  val h, w = nextInt

  val rs = nextInts(h)
  val cs = nextInts(w)

  val grid = Array.fill(h, w)(0)
  var ok = true

  for (i <- rs.indices) {
    val lim = rs(i) min w
    for (j <- 0 until lim) grid(i)(j) = 1
    if (lim < w) grid(i)(lim) = 2
  }

  for (j <- cs.indices) {
    val lim = cs(j) min h
    for (i <- 0 until lim) {
      if (grid(i)(j) == 2) ok = false
      grid(i)(j) = 1
    }
    if (lim < h) {
      if (grid(lim)(j) == 1) ok = false
      grid(lim)(j) = 2
    }
  }
//grid.foreach(g => println(g.mkString))
  val freeCount = grid.flatten.count(_ == 0)

  val res = if (ok) BigInt(2).modPow(freeCount, 1000000007L) else BigInt(0)

  out.println(res)
  out.flush()

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


Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this!

The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters.

In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them.

NoteIn the second test it is acceptable to print i = 2, j = 3.

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[(Char,Char)]()
  var setT = Set[(Char,Char)]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0

  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS.map(x => x._1) contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT.map(x => x._1) contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setT contains Tuple2(s(i),t(i))) && (setS contains Tuple2(t(i),s(i))) && (flag != 2))
        {idxS = i; idxT = i; flag = 2}
      }

      setS += Tuple2(s(i),t(i))
      setT += Tuple2(t(i),s(i))
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS > 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))
          idxS = i
      }

      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
    }
  }

}

/**
 * Created by ronaflx on 15-4-3.
 */
object Codeforces {
  def evalRecord(x: Int): Int = { if (x > 0) 1 else 0 }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val a = io.StdIn.readLine()
    val b = io.StdIn.readLine()
    var record = Array.ofDim[Int](26, 26)
    var hamming: Int = 0
    for (i <- 0 to n - 1) {
      if (a.charAt(i) != b.charAt(i)) {
        record(a.charAt(i).toInt - 97)(b.charAt(i).toInt - 97) = i + 1
        hamming += 1
      }

    }
    var delta: Int = 0
    var posa = -1
    var posb = -1
    for (i <- 0 to 25; j <- 0 to 25) {
      if (i != j) {
        if (delta < evalRecord(record(i)(j)) + evalRecord(record(j)(i)) && record(i)(j) != 0 && record(j)(i) != 0) {
          delta = 2
          posa = record(i)(j)
          posb = record(j)(i)
        }
        for (k <- 0 to 25) {
          if (delta < evalRecord(record(i)(j)) && j != k && record(j)(k) != 0) {
            delta = 1
            posa = record(i)(j)
            posb = record(j)(k)
          }
        }
      }
    }
    println(hamming - delta)
    println(posa + " " + posb)
  }
}

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val s = next.toCharArray
    val t = next.toCharArray
    var curr = 0
    val a = new Array[Array[Int]](27)
    for (i <- 0 until 27) {
      a(i) = new Array[Int](27)
    }
    for (i <- 0 until n) {
      if (s(i) != t(i)) {
        curr += 1
        a(s(i) - 'a')(t(i) - 'a') = i + 1
      }
    }
    for (i <- 0 until a.length) {
      for (j <- i + 1 until a(i).length) {
        if (a(i)(j) >= 1 && a(j)(i) >= 1) {
          out.println(curr - 2)
          out.println(a(i)(j) + " " + a(j)(i))
          return 1
        }
      }
    }

    for (i <- 0 until a.length) {
      var a1 = 0
      var a2 = 0
      for (j <- 0 until a(i).length) {
        a1 = Math.max(a1, a(i)(j))
        a2 = Math.max(a2, a(j)(i))
      }
      if (a1 >= 1 && a2 >= 1) {
        out.println(curr - 1)
        out.println(a1 + " " + a2)
        return 1
      }
    }
    out.println(curr)
    out.println("-1 -1")
    return 1
  }

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

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && flag != 2)
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS > 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)) && idxS != i)
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)) && idxT != i)
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if((s(i) == chr2) && (t(i) == chr1) && idxT != i)
          idxS = i
      }
      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
    }
  }

}

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && (flag != 2))
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS > 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))
          idxS = i
      }
      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
if(idxS == idxT)
print("FUCK")
    }
  }

}

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && flag != 2)
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS > 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)) && idxS != i)
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)) && idxT != i)
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if(s(i) == chr2 && t(i) == chr1)
          idxS = i
      }
      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
    }
  }

}

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && flag != 2)
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

 flag
  match
 {
   case 0 => {println(res); println("-1 -1")}
   case 1 => {
     println(res - 1)
     if(idxS > 0)
     {
       for(i <- 0 until n)
       {
         if((s(i) != t(i)) && (t(i) == s(idxS)))
           idxT = i
       }
       idxS += 1
       idxT += 1
       println(idxS + " " + idxT)
     }
     else {
       for(i <- 0 until n)
       {
         if((s(i) != t(i)) && (s(i) == t(idxT)))
           idxS = i
       }
       idxS += 1
       idxT += 1
       println(idxT + " " + idxS)
     }
   }
   case 2 =>
   {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
     for(i <- 0 until n)
     {
       if(s(i) == chr2 && t(i) == chr1)
         idxS = i
     }
     println(res - 2)
     idxS += 1
     idxT += 1
     println(idxS + " " + idxT)
   }
 }

}

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && (flag != 2))
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS >= 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))
          idxS = i
      }
      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
    }
  }

}

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        else
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && flag != 2)
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS > 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)))
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)))
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if(s(i) == chr2 && t(i) == chr1)
          idxS = i
      }
      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
    }
  }

}

object B524 extends App{

  import scala.collection.mutable.Queue

  val n = readInt
  val s = readLine
  val t = readLine
  var q = List[(Char, Char, Int)]()
  var setS = Set[Char]()
  var setT = Set[Char]()
  var idxS = -1
  var idxT = -1
  var flag = 0
  var res = 0
  for(i <- 0 until n)
  {
    if(s(i) != t(i))
    {
      if(flag == 0) {
        if (setS contains t(i)) {
          idxT = i
          flag += 1
        }
        if (setT contains s(i)) {
          idxS = i
          flag += 1
        }
      }
      else
      {
        if((setS contains t(i)) && (setT contains s(i)) && (flag != 2))
        {idxS = i; idxT = i; flag = 2}
      }

      setS += s(i)
      setT += t(i)
      res += 1
    }
  }

  flag
  match
  {
    case 0 => {println(res); println("-1 -1")}
    case 1 => {
      println(res - 1)
      if(idxS > 0)
      {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (t(i) == s(idxS)) && (idxS != i))
            idxT = i
        }
        idxS += 1
        idxT += 1
        println(idxS + " " + idxT)
      }
      else {
        for(i <- 0 until n)
        {
          if((s(i) != t(i)) && (s(i) == t(idxT)) && (idxT != i))
            idxS = i
        }
        idxS += 1
        idxT += 1
        println(idxT + " " + idxS)
      }
    }
    case 2 =>
    {
      val chr1 = s(idxS)
      val chr2 = t(idxT)
      for(i <- 0 until n)
      {
        if((s(i) == chr2) && (t(i) == chr1) && (idxT != i))
          idxS = i
      }
      println(res - 2)
      idxS += 1
      idxT += 1
      println(idxS + " " + idxT)
    }
  }

}

/**
 * Created by ronaflx on 15-4-3.
 */
object Codeforces {
  def evalRecord(x: Int): Int = { if (x > 0) 1 else 0 }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val a = io.StdIn.readLine()
    val b = io.StdIn.readLine()
    var record = Array.ofDim[Int](26, 26)
    for (i <- 0 to n - 1) {
      if (a.charAt(i) != b.charAt(i)) {
        record(a.charAt(i).toInt - 97)(b.charAt(i).toInt - 97) = i + 1
      }
    }
    var hamming: Int = 0
    var delta: Int = 0
    var posa = -1
    var posb = -1
    record.foreach(hamming += _.count(_ > 0))
    for (i <- 0 to 25; j <- 0 to 25) {
      if (i != j) {
        if (delta < evalRecord(record(i)(j)) + evalRecord(record(j)(i)) && record(i)(j) != 0 && record(j)(i) != 0) {
          delta = 2
          posa = record(i)(j)
          posb = record(j)(i)
        }
        for (k <- 0 to 25) {
          if (delta < evalRecord(record(i)(j)) && j != k && record(j)(k) != 0) {
            delta = 1
            posa = record(i)(j)
            posb = record(j)(k)
          }
        }
      }
    }
    println(hamming - delta)
    println(posa + " " + posb)
  }
}

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val s = next.toCharArray
    val t = next.toCharArray
    var curr = 0
    val a = new Array[Array[Int]](27)
    for (i <- 0 until 27) {
      a(i) = new Array[Int](27)
    }
    for (i <- 0 until n) {
      if (s(i) != t(i)) {
        curr += 1
        a(s(i) - 'a')(t(i) - 'a') = i
      }
    }
    for (i <- 0 until a.length) {
      for (j <- i + 1 until a(i).length) {
        if (a(i)(j) >= 1 && a(j)(i) >= 1) {
          out.println(curr - 2)
          out.println((i + 1) + " " + (j + 1))
          return 1
        }
      }
    }

    for (i <- 0 until a.length) {
      var a1 = 0
      var a2 = 0
      for (j <- 0 until a(i).length) {
        a1 = Math.max(a1, a(i)(j))
        a2 = Math.max(a2, a(j)(i))
      }
      if (a1 >= 1 && a2 >= 1) {
        out.println(curr - 1)
        out.println((a1 + 1) + " " + (a2 + 1))
        return 1
      }
    }
    out.println(curr)
    out.println("-1 -1")
    return 1
  }

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

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val s = next.toCharArray
    val t = next.toCharArray
    var curr = 0
    val t1 = new util.HashMap[Character, ArrayList[Int]]()
    val pos = new util.ArrayList[Int]()
    for (i <- 0 until n) {
      if (s(i) != t(i)) {
        pos.add(i)
        curr += 1
        if (!t1.containsKey(t(i))) {
          val list = new util.ArrayList[Int]()
          list.add(i)
          t1.put(t(i), list)
        } else {
          t1.get(t(i)).add(i)
        }
      }
    }
    var i1 = -1
    var i2 = -1
    var min = curr
    for (i <- 0 until pos.size()) {
      val s1: Char = s(pos.get(i))
      if (null != t1.get(s1)) {
        val ind = t1.get(s1)
        for (j <- 0 until ind.size()) {
          if (s(ind.get(j)) == t(i)) {
            if (curr - 2 < min) {
              min = curr - 2
              i1 = i
              i2 = ind.get(j)
              out.println(min)
              out.println((i1 + 1) + " " + (i2 + 1))
              return 1
            }
          } else {
            if (curr - 1 < min) {
              min = curr - 1
              i1 = i
              i2 = ind.get(j)
            }
          }
        }
      }
    }
    if (min == curr) {
      out.println(curr)
      out.println("-1 -1")
    } else {
      out.println(min)
      out.println((i1 + 1) + " " + (i2 + 1))
    }
    return 1
  }

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

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val s = next.toCharArray
    val t = next.toCharArray
    var curr = 0
    val a = new Array[Array[Int]](27)
    for (i <- 0 until 27) {
      a(i) = new Array[Int](27)
    }
    for (i <- 0 until n) {
      if (s(i) != t(i)) {
        curr += 1
        a(s(i) - 'a')(t(i) - 'a') = i + 1
      }
    }
    for (i <- 0 until a.length) {
      for (j <- i + 1 until a(i).length) {
        if (a(i)(j) >= 1 && a(j)(i) >= 1) {
          out.println(curr - 2)
          out.println(i + " " + j)
          return 1
        }
      }
    }

    for (i <- 0 until a.length) {
      var a1 = 0
      var a2 = 0
      for (j <- 0 until a(i).length) {
        a1 = Math.max(a1, a(i)(j))
        a2 = Math.max(a2, a(j)(i))
      }
      if (a1 >= 1 && a2 >= 1) {
        out.println(curr - 1)
        out.println(a1 + " " + a2)
        return 1
      }
    }
    out.println(curr)
    out.println("-1 -1")
    return 1
  }

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

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val s = next.toCharArray
    val t = next.toCharArray
    var curr = 0
    val t1 = new util.HashMap[Character, ArrayList[Int]]()
    val pos = new util.ArrayList[Int]()
    for (i <- 0 until n) {
      if (s(i) != t(i)) {
        pos.add(i)
        curr += 1
        if (!t1.containsKey(t(i))) {
          val list = new util.ArrayList[Int]()
          list.add(i)
          t1.put(t(i), list)
        } else {
          t1.get(t(i)).add(i)
        }
      }
    }
    var i1 = -1
    var i2 = -1
    var min = curr
    for (i <- 0 until pos.size()) {
      val s1: Char = s(pos.get(i))
      if (null != t1.get(s1)) {
        val ind = t1.get(s1)
        for (j <- 0 until ind.size()) {
          if (s(ind.get(j)) == t(i)) {
            if (curr - 2 < min) {
              min = curr - 2
              i1 = pos.get(i)
              i2 = ind.get(j)
              out.println(min)
              out.println((i1 + 1) + " " + (i2 + 1))
              return 1
            }
          } else {
            if (curr - 1 < min) {
              min = curr - 1
              i1 = pos.get(i)
              i2 = ind.get(j)
            }
          }
        }
      }
    }
    if (min == curr) {
      out.println(curr)
      out.println("-1 -1")
    } else {
      out.println(min)
      out.println((i1 + 1) + " " + (i2 + 1))
    }
    return 1
  }

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