Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.

The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.

For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).

import java.math.BigInteger
import java.util.Random

import scala.io.StdIn._

object CF291C extends App {
  val N = 600001
  val MOD = BigInteger.probablePrime(50, new Random()).longValue()
  val BASE = 4L

  val deg = new Array[Long](N)
  deg(0) = 1
  (1 until N) foreach (i => deg(i) = (deg(i - 1) * BASE) % MOD)

  def getHash(s: String): Long = {
    var hash = 0L
    (0 until s.length) foreach { i =>
      hash = (BASE * hash + (s.charAt(i) - 'a' + 1)) % MOD
    }
    hash
  }

  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val hashes = scala.collection.mutable.Set.empty[Long]
  (0 until n) foreach { i =>
    val str = readLine()
    val hash = getHash(str)
    hashes.add(hash)
  }

  (0 until m) foreach { _ =>
    val s = readLine()
    val hash = getHash(s)

    var found = false
    (0 until s.length) foreach { i =>
      List('a', 'b', 'c') foreach { c =>
        if (s.charAt(i) != c) {
          var now = (c - s.charAt(i)) * deg(s.length - 1 - i)
          now += MOD * 3
          now += hash
          now %= MOD
          if (hashes.contains(now)) {
            found = true
          }
        }
      }
    }

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

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

object C {

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

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

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

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

  val MODULO = (1e9 + 7).toInt

  def sum(a: Int, b: Int): Int = {
    val sum = a + b
    val res = if (sum < MODULO) sum else sum - MODULO
    return res
  }

  def multiply(a: Int, b: Int): Int = {
    return (1L * a * b % MODULO).toInt
  }

  def calcHash(ch: Array[Char]): Int = {
    var hash = 0
    val len = ch.length
    for (i <- 0 until len) {
      hash = multiply(hash, 31)
      hash = sum(hash, (ch(i) - 'a') + 1)
    }
    return hash
  }

  class HashString(val s: Array[Char], val hash: Int) {

    def this(xs: Array[Char]) {
      this(xs, calcHash(xs))
    }

    override def hashCode(): Int = hash

    override def equals(obj: scala.Any): Boolean = {
      val s1 = obj.asInstanceOf[HashString]
      return Arrays.equals(s, s1.s)
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val pow = new Array[Int](6e5.toInt)
    pow(0) = 1
    for (i <- 1 until pow.length) {
      pow(i) = multiply(pow(i - 1), 31)
    }
    val set = new util.HashSet[HashString]()
    for (i <- 0 until n) {
      set.add(new HashString(next.toCharArray))
    }
    (0 until m).foreach(_ => {
      val t = next.toCharArray
      val hash = calcHash(t)
      var flag = false
      for (i <- 0 until t.length
           if !flag) {
        val prev = t(i)
        for (j <- 'a' to 'z'
             if !flag) {
          if (j != prev) {
            t(i) = j
            val updHash = sum(hash, multiply(sum(MODULO - prev, j), pow(t.length - i - 1)))
            if (set.contains(new HashString(t, updHash))) {
              flag = true
            }
          }
        }
        t(i) = prev
      }
      if (flag) {
        println("YES")
      } else {
        println("NO")
      }
    })
    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.util.Scanner

import scala.collection.mutable._

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  val cache = new HashSet[String]
  val ts = new HashSet[String]

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val memo = new ArrayBuffer[String]

    (0 until n) foreach { i =>
      val str = sc.nextLine()
      memo.append(str)
    }

    val ans = Array.tabulate[String](q)(_ => "NO")
    val queries = new HashMap[String, ArrayBuffer[Int]]

    val sizes = new HashSet[Int]
    (0 until q) foreach {idx =>
      val query = sc.nextLine()
      if (queries.contains(query)) {
        queries.get(query).get.append(idx)
      } else {
        val buff = new ArrayBuffer[Int]
        buff.append(idx)
        queries.put(query, buff)
      }
      sizes.add(query.size)
    }

    var loop = true
    for (m<-0 until memo.size if loop) {
      val str = memo(m)

      if (!cache.contains(str) && sizes.contains(str.length)) {
        if (str.length > 10000) {
          check(str, queries, ans)
        } else {
          val charBuff = str.toCharArray
          for (i <- 0 until str.length) {

            val ch = str(i)

            if (ch == 'a') {
              populate(charBuff, i, queries, ans, 'b', 'c')
            }
            if (ch == 'b') {
              populate(charBuff, i, queries, ans, 'a', 'c')
            }
            if (ch == 'c') {
              populate(charBuff, i, queries, ans, 'a', 'b')
            }

          }
        }
        cache.add(str)
      }

      if (ts.size == queries.size) {
        loop = false
      }
    }

    for( a<-0 until ans.length) {
      println(ans(a))
    }

  }

  def check(str: String, queries: HashMap[String, ArrayBuffer[Int]], ans: Array[String]): Unit = {
    queries.foreach {
      case (k,v) =>
        if (k.length == str.length) {
          var diff = 0
          var loop = true
          for (i<-0 until str.length if loop) {
            if (str(i) != k(i)) {
              diff += 1
            }
            if (diff > 1) {
              loop = false
            }
          }
          if (diff == 1) {
            v.foreach {
              idx => ans(idx) = "YES"
            }
          }
        }
    }
  }
  def populate(charBuff: Array[Char], ind: Int, queries: HashMap[String, ArrayBuffer[Int]],
               ans: Array[String], c1: Char, c2: Char): Unit = {
    val old = charBuff(ind)

    charBuff(ind) = c1
    val t1 = String.valueOf(charBuff)

    charBuff(ind) = c2
    val t2 = String.valueOf(charBuff)

    if (queries.contains(t1) && !ts.contains(t1)) {
      val buff = queries.get(t1).get
      buff.foreach { idx =>
        ans(idx) = "YES"
      }
      ts.add(t1)
    }

    if (queries.contains(t2) && !ts.contains(t2)) {
      val buff = queries.get(t2).get
      buff.foreach { idx =>
        ans(idx) = "YES"
      }
      ts.add(t2)
    }
    charBuff(ind) = old

  }

}

import java.math.BigInteger
import java.util.Random

import scala.io.StdIn._

object CF291C extends App {
  val N = 600001
  val MOD = BigInteger.probablePrime(50, new Random()).longValue()
  val BASE = 4L

  val deg = new Array[Long](N)
  deg(0) = 1
  (1 until N) foreach (i => deg(i) = (deg(i - 1) * BASE) % MOD)

  def getHash(s: String): Long = {
    var hash = 0L
    (0 until s.length) foreach { i =>
      hash = (BASE * hash + (s.charAt(i) - 'a' + 1)) % MOD
    }
    hash
  }

  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val hashes = scala.collection.mutable.Set[Long](n)
  (0 until n) foreach { i =>
    val str = readLine()
    val hash = getHash(str)
    hashes.add(hash)
  }

  (0 until m) foreach { _ =>
    val s = readLine()
    val hash = getHash(s)

    var found = false
    (0 until s.length) foreach { i =>
      List('a', 'b', 'c') foreach { c =>
        if (s.charAt(i) != c) {
          var now = (c - s.charAt(i)) * deg(s.length - 1 - i)
          now += MOD * 3
          now += hash
          now %= MOD
          if (hashes.contains(now)) {
            found = true
          }
        }
      }
    }

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

}

object CF291C extends App {
  val N = 600001
  val MOD = 1000000000000000007L
  val p = new Array[Long](N)
  p(0) = 1
  (1 until N) foreach (i => p(i) = p(i - 1) * 4 % MOD)

  def getHash(s: String): Long = {
    var hash = 0L
    (0 until s.length) foreach { i =>
      hash = (hash + (s.charAt(i) - 'a' + 1) * p(i)) % MOD
    }
    hash
  }

  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val hashes = new Array[Long](n)
  (0 until n) foreach { i =>
    val str = readLine()
    val hash = getHash(str)
    hashes(i) = hash
  }

  val sortedHashes = hashes.sorted

  (0 until m) foreach { _ =>
    val s = readLine()
    var found = false

    (0 until s.length) foreach { i =>
      List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>
        val str = new StringBuilder(s)
        str.setCharAt(i, c)
        val hash = getHash(str.toString())
        if (sortedHashes.contains(hash)) {
          found = true
        }
      }
    }

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

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

  val hashes = new Array[Int](n)
  (0 until n) foreach { i =>
    val str = readLine()
    val hash = str.hashCode
    hashes(i) = hash
  }

  val sortedHashes = hashes.sorted

  (0 until m) foreach { _ =>
    val s = readLine()
    var found = false

    (0 until s.length) foreach { i =>
      List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>
        val str = new StringBuilder(s)
        str.setCharAt(i, c)
        val hash = str.toString().hashCode()
        if (sortedHashes.contains(hash)) {
          found = true
        }
      }
    }

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

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

  val set = scala.collection.mutable.Set.empty[Int]
  (0 until n) foreach { _ =>
    val s = readLine().hashCode
    set += s
  }

  (0 until m) foreach { _ =>
    val s = readLine()
    var found = false

    (0 until s.length) foreach { i =>
      List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>
        val str = new StringBuilder(s)
        str.setCharAt(i, c)
        val hash = str.toString().hashCode()
        if (set.contains(hash)) {
          found = true
        }
      }
    }

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

import java.math.BigInteger
import java.util.Random

import scala.io.StdIn._

object CF291C extends App {
  val N = 600001
  val MOD = BigInteger.probablePrime(51, new Random()).longValue()
  val BASE = 4L

  val deg = new Array[Long](N)
  deg(0) = 1
  (1 until N) foreach (i => deg(i) = (deg(i - 1) * BASE) % MOD)

  def getHash(s: String): Long = {
    var hash = 0L
    (0 until s.length) foreach { i =>
      hash = (BASE * hash + (s.charAt(i) - 'a' + 1)) % MOD
    }
    hash
  }

  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val hashes = scala.collection.mutable.Set[Long](n)
  (0 until n) foreach { i =>
    val str = readLine()
    val hash = getHash(str)
    hashes.add(hash)
  }

  (0 until m) foreach { _ =>
    val s = readLine()
    val hash = getHash(s)

    var found = false
    (0 until s.length) foreach { i =>
      List('a', 'b', 'c') foreach { c =>
        if (s.charAt(i) != c) {
          var now = (c - s.charAt(i)) * deg(s.length - 1 - i)
          now += MOD * 3
          now += hash
          now %= MOD
          if (hashes.contains(now)) {
            found = true
          }
        }
      }
    }

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

}

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

  val set = scala.collection.mutable.Set.empty[String]
  (0 until n) foreach { _ =>
    val s = readLine()
    set += s
  }

  (0 until m) foreach { _ =>
    val s = readLine()
    var found = false

    (0 until s.length) foreach { i =>
      List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>
        val str = new StringBuilder(s)
        str.setCharAt(i, c)
        if (set.contains(str.toString())) {
          found = true
        }
      }
    }

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

import scala.io.StdIn._

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

  def fits(s1: String, s2: String): Boolean = {
    if (s1.length != s2.length) {
      false
    }

    var n = 0
    (0 until s1.length) foreach { i =>
      if (s1.charAt(i) != s2.charAt(i)) n += 1
      if (n > 1) false
    }

    true
  }

  val CUTOFF = 700
  val small = scala.collection.mutable.Set.empty[String]
  val big = scala.collection.mutable.Set.empty[String]
  (0 until n) foreach { _ =>
    val str = readLine()
    if (str.length < CUTOFF) small.add(str)
    else big.add(str)
  }

  (0 until m) foreach { _ =>
    val s = readLine()

    if (s.length < CUTOFF) {
      var found = false

      (0 until s.length) foreach { i =>
        List('a', 'b', 'c') foreach { c =>
          if (s.charAt(i) != c) {
            val str = new StringBuilder(s)
            str.setCharAt(i, c)
            if (small.contains(str.toString())) {
              found = true
            }
          }
        }
      }

      if (found) println("YES")
      else println("NO")

    } else {
      var found = false
      big.toStream.takeWhile(_ => !found) foreach { str =>
        if (fits(s, str)) found = true
      }
      if (found) println("YES")
      else println("NO")
    }
  }
}

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

  val hashes = new Array[String](n)
  (0 until n) foreach { i =>
    val str = readLine()
    val hash = str.hashCode
    hashes(i) = str
  }

  val sortedHashes = hashes.sorted

  (0 until m) foreach { _ =>
    val s = readLine()
    var found = false

    (0 until s.length) foreach { i =>
      List('a', 'b', 'c').toStream.takeWhile(_ => !found) foreach { c =>
        val str = new StringBuilder(s)
        str.setCharAt(i, c)
        val hash = str.toString().hashCode()
        if (sortedHashes.contains(str.toString())) {
          found = true
        }
      }
    }

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

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

object C {

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

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

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

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

  val MODULO = (1e7 + 9).toInt

  def sum(a: Int, b: Int): Int = {
    val sum = a + b
    val res = if (sum < MODULO) sum else sum - MODULO
    return res
  }

  def multiply(a: Int, b: Int): Int = {
    return (1L * a * b % MODULO).toInt
  }

  def calcHash(ch: Array[Char]): Int = {
    var hash = 0
    val len = ch.length
    for (i <- 0 until len) {
      hash = multiply(hash, 31)
      hash = sum(hash, ch(i) - 'a' + 1)
    }
    return hash
  }

  class HashString(val s: Array[Char], val hash: Int) {

    def this(xs: Array[Char]) {
      this(xs, calcHash(xs))
    }

    override def hashCode(): Int = hash

    override def equals(obj: scala.Any): Boolean = {
      val s1 = obj.asInstanceOf[HashString]
      return Arrays.equals(s, s1.s)
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val pow = new Array[Int](3e5.toInt)
    pow(0) = 1
    for (i <- 1 until pow.length) {
      pow(i) = multiply(pow(i - 1), 31)
    }
    val set = new util.HashSet[HashString]()
    for (i <- 0 until n) {
      set.add(new HashString(next.toCharArray))
    }
    (0 until m).foreach(_ => {
      val t = next.toCharArray
      val hash = calcHash(t)
      var i = 0
      var flag = true
      while (flag && i < t.length) {
        val c = t(i)
        for (j <- 'a' to 'z') {
          if (j != c) {
            t(i) = j
            val updHash = sum(hash, multiply(sum(MODULO - c, c), pow(t.length - i - 1)))
            if (set.contains(new HashString(t, updHash))) {
              flag = false
            }
          }
        }
        t(i) = c
        i += 1
      }
      if (flag) {
        println("YES")
      } else {
        println("NO")
      }
    })
    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.util.Scanner

import scala.collection.mutable.HashMap

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val mapN = new HashMap[Int, (Int,Int,Int)]
    (0 until n) foreach { i =>

      val str = sc.nextLine()
      val as = str.filter(c => c == 'a').size
      val bs = str.filter(c => c == 'b').size
      val cs = str.filter(c => c == 'c').size
      mapN.put(i, (as,bs,cs))
    }

    (0 until q) foreach {_ =>
      val query = sc.nextLine()

      val qa = query.filter(c => c == 'a').size
      val qb = query.filter(c => c == 'b').size
      val qc = query.filter(c => c == 'c').size

      var loop = true
      var ans = "NO"
      for (i<-0 until n if loop) {
        val out = mapN.get(i).get
        if ((math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc)) <= 2 && qa + qb + qc == out._1 + out._2 + out._3) {
          ans = "YES"
          loop = false
        }
      }

      println(ans)

    }

  }

}

import java.util.Scanner

import scala.collection.mutable._

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val mapN = new HashMap[Int, ArrayBuffer[(Int,Int,Int, String)]]
    (0 until n) foreach { i =>

      val str = sc.nextLine()
      val as = str.filter(c => c == 'a').size
      val bs = str.filter(c => c == 'b').size
      val cs = str.filter(c => c == 'c').size
      val l = str.length
      if (mapN.contains(l)) {
        mapN.get(l).get.append((as,bs,cs, str))
      } else {
        val buff = new ArrayBuffer[(Int,Int,Int, String)]
        buff.append((as, bs, cs, str))
        mapN.put(l, buff)
      }
    }

    val cache = new HashMap[String, String]
    (0 until q) foreach {_ =>
      val query = sc.nextLine()

      if (cache.contains(query)) {
        println(cache.get(query).get)
      } else {

        var qa = 0
        var qb = 0
        var qc = 0

        query.foreach { j =>
          if (j == 'a') qa += 1
          if (j == 'b') qb += 1
          if (j == 'c') qc += 1
        }

        val sub = mapN.get(query.length).getOrElse(null)
        var loop = true
        var ans = "NO"

        if (sub != null) {
          for (i <- 0 until sub.length if loop) {
            val out = sub(i)
            val diff = (math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc))

            if ((diff == 2 || diff == 1) && areEq(out._4, query)) {
              ans = "YES"
              loop = false
            }
          }
        }
        cache.put(query, ans)
        println(ans)
      }

    }

  }

  def areEq(s: String, q: String): Boolean = {
    var diff = 0
    var loop = true
    val mid = s.length/2 - 1
    for (i <- 0 to mid if loop) {
      if (s(i) != q(i) || s(s.length-i-2) != q(q.length -i -2)) {
        diff += 1
      }
      if (diff > 1)
        loop = false
    }

    return diff == 1
  }

}

import java.util.Scanner

import scala.collection.mutable._

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val memo = new ArrayBuffer[String]

    (0 until n) foreach { i =>
      val str = sc.nextLine()
      memo.append(str)
    }

    val ans = Array.tabulate[String](q)(_ => "NO")
    val queries = new HashMap[String, Int]

    (0 until q) foreach {idx =>
      val query = sc.nextLine()
      queries.put(query, idx)
    }

    memo.foreach {str =>

      for (i<- 0 until str.length) {

        val ch = str(i)
        val pre = if (i == 0) "" else str.substring(0,i)
        val suffix = str.substring(i+1)

        if (ch == 'a') {
          populate(pre, suffix, queries,ans, 'b','c')
        }
        if (ch == 'b') {
          populate(pre, suffix, queries,ans, 'a', 'c')
        }
        if (ch == 'c') {
          populate(pre, suffix, queries,ans, 'a', 'b')
        }
      }
    }

    for( a<-0 until ans.length) {
      println(ans(a))
    }

  }

  def populate(pre: String, suffix: String, queries: HashMap[String, Int],
               ans: Array[String], c1: Char, c2: Char): Unit = {
    val t1 = pre+c1+suffix
    val t2 = pre+c2+suffix
    if (queries.contains(t1)) {
      ans(queries.get(t1).get) = "YES"
    }
    if (queries.contains(t2)) {
      ans(queries.get(t2).get) = "YES"
    }
  }

}

import java.util.Scanner

import scala.collection.mutable._

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val mapN = new HashMap[Int, ArrayBuffer[(Int,Int,Int, String)]]
    (0 until n) foreach { i =>

      val str = sc.nextLine()
      val as = str.filter(c => c == 'a').size
      val bs = str.filter(c => c == 'b').size
      val cs = str.filter(c => c == 'c').size
      val l = str.length
      if (mapN.contains(l)) {
        mapN.get(l).get.append((as,bs,cs, str))
      } else {
        val buff = new ArrayBuffer[(Int,Int,Int, String)]
        buff.append((as, bs, cs, str))
        mapN.put(l, buff)
      }
    }

    val cache = new HashMap[String, String]
    (0 until q) foreach {_ =>
      val query = sc.nextLine()

      if (cache.contains(query)) {
        println(cache.get(query).get)
      } else {

        var qa = 0
        var qb = 0
        var qc = 0

        query.foreach { j =>
          if (j == 'a') qa += 1
          if (j == 'b') qb += 1
          if (j == 'c') qc += 1
        }

        val sub = mapN.get(query.length).getOrElse(null)
        var loop = true
        var ans = "NO"

        if (sub != null) {
          for (i <- 0 until sub.length if loop) {
            val out = sub(i)
            val diff = (math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc))

            val adiff = math.abs(out._1 - qa)
            val bdiff = math.abs(out._2 - qb)
            val cdiff = math.abs(out._2 - qc)

            if ((diff == 2 || diff == 1) && !(adiff > 1) && !(bdiff > 1) && !(cdiff > 1) && areEq(out._4, query)) {
              ans = "YES"
              loop = false
            }
          }
        }
        cache.put(query, ans)
        println(ans)
      }

    }

  }

  def areEq(s: String, q: String): Boolean = {
    var diff = 0
    var loop = true
    for (i <- 0 until s.length if loop) {
      if (s(i) != q(i)) {
        diff += 1
      }
      if (diff > 1)
        loop = false
    }

    return diff == 1
  }

}

import java.util.Scanner

import scala.collection.mutable.HashMap

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val mapN = new HashMap[Int, (Int,Int,Int)]
    (0 until n) foreach { i =>

      val str = sc.nextLine()
      val as = str.filter(c => c == 'a').size
      val bs = str.filter(c => c == 'b').size
      val cs = str.filter(c => c == 'c').size
      mapN.put(i, (as,bs,cs))
    }

    (0 until q) foreach {_ =>
      val query = sc.nextLine()

      val qa = query.filter(c => c == 'a').size
      val qb = query.filter(c => c == 'b').size
      val qc = query.filter(c => c == 'c').size

      var loop = true
      var ans = "NO"
      for (i<-0 until n if loop) {
        val out = mapN.get(i).get
        if ((math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc)) == 2 && qa + qb + qc == out._1 + out._2 + out._3) {
          ans = "YES"
          loop = false
        }
      }

      println(ans)

    }

  }

}

import java.util.Scanner

import scala.collection.mutable._

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  val cache = new HashSet[String]

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val memo = new ArrayBuffer[String]

    (0 until n) foreach { i =>
      val str = sc.nextLine()
      memo.append(str)
    }

    val ans = Array.tabulate[String](q)(_ => "NO")
    val queries = new HashMap[String, ArrayBuffer[Int]]

    (0 until q) foreach {idx =>
      val query = sc.nextLine()
      if (queries.contains(query)) {
        queries.get(query).get.append(idx)
      } else {
        val buff = new ArrayBuffer[Int]
        buff.append(idx)
        queries.put(query, buff)
      }

    }

    memo.foreach {str =>

      if (!cache.contains(str)) {
        for (i <- 0 until str.length) {

          val ch = str(i)
          val pre = if (i == 0) "" else str.substring(0, i)
          val suffix = str.substring(i + 1)

          if (ch == 'a') {
            populate(pre, suffix, queries, ans, 'b', 'c')
          }
          if (ch == 'b') {
            populate(pre, suffix, queries, ans, 'a', 'c')
          }
          if (ch == 'c') {
            populate(pre, suffix, queries, ans, 'a', 'b')
          }
        }
        cache.add(str)
      }
    }

    for( a<-0 until ans.length) {
      println(ans(a))
    }

  }

  def populate(pre: String, suffix: String, queries: HashMap[String, ArrayBuffer[Int]],
               ans: Array[String], c1: Char, c2: Char): Unit = {
    val t1 = pre+c1+suffix
    val t2 = pre+c2+suffix
    if (queries.contains(t1)) {
      val buff = queries.get(t1).get
      buff.foreach { idx =>
        ans(idx) = "YES"
      }
      cache.add(t1)
    }
    if (queries.contains(t2)) {
      val buff = queries.get(t2).get
      buff.foreach { idx =>
        ans(idx) = "YES"
      }
      cache.add(t2)
    }

  }

}

import java.util.Scanner

import scala.collection.mutable.HashMap

/**
 * Created by dimitar on 2/14/15.
 */
object Queries {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val q = sc.nextInt()

    sc.nextLine()
    val mapN = new HashMap[Int, (Int,Int,Int)]
    (0 until n) foreach { i =>

      val str = sc.nextLine()
      val as = str.filter(c => c == 'a').size
      val bs = str.filter(c => c == 'b').size
      val cs = str.filter(c => c == 'c').size
      mapN.put(i, (as,bs,cs))
    }

    (0 until q) foreach {_ =>
      val query = sc.nextLine()

      val qa = query.filter(c => c == 'a').size
      val qb = query.filter(c => c == 'b').size
      val qc = query.filter(c => c == 'c').size

      var loop = true
      var ans = "NO"
      for (i<-0 until n if loop) {
        val out = mapN.get(i).get
        val diff = (math.abs(out._1 - qa) + math.abs(out._2 - qb) + math.abs(out._3 - qc))
        if ( (diff == 1 || diff == 2) && qa + qb + qc == out._1 + out._2 + out._3) {
          ans = "YES"
          loop = false
        }
      }

      println(ans)

    }

  }

}


Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.There are $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ on Bob's homework paper, where $$$n$$$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $$$2$$$ numbers. Suppose the numbers are divided into $$$m$$$ groups, and the sum of the numbers in the $$$j$$$-th group is $$$s_j$$$. Bob's aim is to minimize the sum of the square of $$$s_j$$$, that is $$$$$$\sum_{j = 1}^{m} s_j^2.$$$$$$Bob is puzzled by this hard problem. Could you please help him solve it?

The first line contains an even integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$), denoting that there are $$$n$$$ integers on Bob's homework paper. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^4$$$), describing the numbers you need to deal with.

A single line containing one integer, denoting the minimum of the sum of the square of $$$s_j$$$, which is $$$$$$\sum_{i = j}^{m} s_j^2,$$$$$$ where $$$m$$$ is the number of groups.

NoteIn the first sample, one of the optimal solutions is to divide those $$$4$$$ numbers into $$$2$$$ groups $$$\{2, 8\}, \{5, 3\}$$$. Thus the answer is $$$(2 + 8)^2 + (5 + 3)^2 = 164$$$.In the second sample, one of the optimal solutions is to divide those $$$6$$$ numbers into $$$3$$$ groups $$$\{1, 2\}, \{1, 2\}, \{1, 2\}$$$. Thus the answer is $$$(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$$$.

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 A = na(N)
    sort(A)

    var ans = 0L
    REP(N / 2) { i =>
      val s = A(i) + A(N - 1 - i)
      ans += s.toLong * s
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

import java.util.Scanner

object Main {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    scan.nextLine
    val xs: Array[Int] = (scan.nextLine split ' ' map (_.toInt)).sorted
    val ans = (xs.take(n / 2) zip xs.drop(n / 2).reverse map { case (x, y) => (x + y).toLong * (x + y) }).sum
    println(ans)
  }
}


One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!

The first line contains one integer n (1  ≤ n  ≤  2·105) — the number of seasons. The second line contains n integers separated by space a1, a2, ..., an (1 ≤ ai ≤ 109) — number of episodes in each season.

Print one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.

NotePossible pairs in the second example:  x = 1, y = 2 (season 1 episode 2  season 2 episode 1);  x = 2, y = 3 (season 2 episode 3  season 3 episode 2);  x = 1, y = 3 (season 1 episode 3  season 3 episode 1). In the third example:  x = 1, y = 2 (season 1 episode 2  season 2 episode 1);  x = 1, y = 3 (season 1 episode 3  season 3 episode 1).

object Solution {
  import scala.collection.mutable.ListBuffer

  def main(args: Array[String]) {
    val r = new Reader
    val n = r.read[Int]
    val as = r.read[Array[Int]](n).map(x => x.min(n))

    val ss = (0 until as.length).foldLeft(Array.fill(n)(ListBuffer[Int]())) {
      case (arr, i) => { arr(as(i) - 1) += i + 1; arr }
    }

    val bs = BIT.fill(n)(1)

    val res = (0 until as.length).foldLeft(0L) {
      case (res, i) => {
        val res1 = res + bs(as(i)).toLong
        ss(i).map(bs.update(_, -1))
        if (i < as(i)) res1 - 1L else res1
      }
    }

    println(res / 2)
  }
}

final class BIT(arr: Array[Int]) {
  private val _tree = Array.fill(arr.length + 1)(0)

  for (i <- 1 until _tree.length) {
    _tree(i) += arr(i - 1)
    if (i + range(i) < _tree.length) _tree(i + range(i)) += _tree(i)
  }

  def apply(i: Int): Int = {
    @annotation.tailrec
    def go(acc: Int, i: Int): Int = if (i <= 0) acc else go(acc + _tree(i), i - range(i))

    go(0, i)
  }

  def apply(i: Int, j: Int): Int = apply(j) - apply(i - 1)

  @annotation.tailrec
  def update(i: Int, x: Int): Unit = {
    if (i < _tree.length) {
      _tree(i) += x
      update(i + range(i), x)
    }
  }

  private def range(n: Int) = n & (~n + 1)
}

object BIT {
  def fill(n: Int)(x: Int) = new BIT(Array.fill(n)(x))
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Solution {
  import scala.collection.mutable.ListBuffer

  def main(args: Array[String]) {
    val r = new Reader
    val n = r.read[Int]
    val as = r.read[Array[Int]](n).map(x => x.min(n))

    val ss = (0 until as.length).foldLeft(Array.fill(n)(ListBuffer[Int]())) {
      case (arr, i) => { arr(as(i) - 1) += i + 1; arr }
    }

    val bs = BIT.fill(n)(1)

    val res = (0 until as.length).foldLeft(0) {
      case (res, i) => {
        val res1 = res + bs(as(i))
        ss(i).map(bs.update(_, -1))
        if (i < as(i)) res1 - 1 else res1
      }
    }

    println(res / 2)
  }
}

final class BIT(arr: Array[Int]) {
  private val _tree = Array.fill(arr.length + 1)(0)

  for (i <- 1 until _tree.length) {
    _tree(i) += arr(i - 1)
    if (i + range(i) < _tree.length) _tree(i + range(i)) += _tree(i)
  }

  def apply(i: Int): Int = {
    @annotation.tailrec
    def go(acc: Int, i: Int): Int = if (i <= 0) acc else go(acc + _tree(i), i - range(i))

    go(0, i)
  }

  def apply(i: Int, j: Int): Int = apply(j) - apply(i - 1)

  @annotation.tailrec
  def update(i: Int, x: Int): Unit = {
    if (i < _tree.length) {
      _tree(i) += x
      update(i + range(i), x)
    }
  }

  private def range(n: Int) = n & (~n + 1)
}

object BIT {
  def fill(n: Int)(x: Int) = new BIT(Array.fill(n)(x))
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Solution {
  import scala.collection.mutable.ListBuffer

  def main(args: Array[String]) {
    val r = new Reader
    val n = r.read[Int]
    val as = r.read[Array[Int]](n).map(x => x.min(n))

    val ss = (0 until as.length).foldLeft(Array.fill(n)(ListBuffer[Int]())) {
      case (arr, i) => { arr(as(i) - 1) += i + 1; arr }
    }

    val bs = BIT.fill(n)(1)

    val res = (0 until as.length).foldLeft(0) {
      case (res, i) => {
        val res1 = res + bs(as(i))
        ss(i).map(bs.update(_, -1))
        if (i <= as(i)) res1 - 1 else res1
      }
    }

    println(res / 2)
  }
}

final class BIT(arr: Array[Int]) {
  private val _tree = Array.fill(arr.length + 1)(0)

  for (i <- 1 until _tree.length) {
    _tree(i) = if (i % 2 == 0) _tree(i - 2) + arr(i - 2) + arr(i - 1) else arr(i - 1)
  }

  def apply(i: Int): Int = {
    @annotation.tailrec
    def go(acc: Int, i: Int): Int = if (i <= 0) acc else go(acc + _tree(i), i - range(i))

    go(0, i)
  }

  def apply(i: Int, j: Int): Int = apply(j) - apply(i - 1)

  @annotation.tailrec
  def update(i: Int, x: Int): Unit = {
    if (i < _tree.length) {
      _tree(i) += x
      update(i + range(i), x)
    }
  }

  def toList = _tree.toList

  private def range(n: Int) = n & (~n + 1)
}

object BIT {
  def fill(n: Int)(x: Int) = new BIT(Array.fill(n)(x))
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}


A plane is flying at a constant height of $$$h$$$ meters above the ground surface. Let's consider that it is flying from the point $$$(-10^9, h)$$$ to the point $$$(10^9, h)$$$ parallel with $$$Ox$$$ axis.A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to $$$Ox$$$ axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.There are ascending air flows on certain segments, each such segment is characterized by two numbers $$$x_1$$$ and $$$x_2$$$ ($$$x_1 < x_2$$$) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along $$$Ox$$$ axis, covering one unit of distance every second.     If the glider jumps out at $$$1$$$, he will stop at $$$10$$$. Otherwise, if he jumps out at $$$2$$$, he will stop at $$$12$$$. Determine the maximum distance along $$$Ox$$$ axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is $$$0$$$.

The first line contains two integers $$$n$$$ and $$$h$$$ $$$(1 \le n \le 2\cdot10^{5}, 1 \le h \le 10^{9})$$$ — the number of ascending air flow segments and the altitude at which the plane is flying, respectively. Each of the next $$$n$$$ lines contains two integers $$$x_{i1}$$$ and $$$x_{i2}$$$ $$$(1 \le x_{i1} < x_{i2} \le 10^{9})$$$ — the endpoints of the $$$i$$$-th ascending air flow segment. No two segments intersect, and they are given in ascending order.

Print one integer — the maximum distance along $$$Ox$$$ axis that the glider can fly from the point where he jumps off the plane to the point where he lands if he can start his flight at any integer coordinate.

NoteIn the first example if the glider can jump out at $$$(2, 4)$$$, then the landing point is $$$(12, 0)$$$, so the distance is $$$12-2 = 10$$$.In the second example the glider can fly from $$$(16,10)$$$ to $$$(34,0)$$$, and the distance is $$$34-16=18$$$.In the third example the glider can fly from $$$(-100,1000000000)$$$ to $$$(1999999899,0)$$$, so the distance is $$$1999999899-(-100)=1999999999$$$.

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, H = ni()

    case class Seg(l: Int, r: Int) {
      def len = r - l
    }

    val S = Array.ofDim[Seg](N)
    rep(N) { i =>
      val l, r = ni()
      S(i) = Seg(l, r)
    }

    var l, r = 0
    var sum = S(0).len
    var mx = sum
    var len = 0
    while(l < N) {
      while (r + 1 < N && len + (S(r + 1).l - S(r).r) < H) {
        len += S(r + 1).l - S(r).r
        r += 1
        sum += S(r).len
      }
      mx = max(mx, sum)
      sum -= S(l).len
      if (l + 1 < N) len -= S(l + 1).l - S(l).r
      l += 1
    }

    out.println(mx + H)
  }

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

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

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

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

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


You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.

Input begins with an integer N (2 ≤ N ≤ 3·105), the number of days. Following this is a line with exactly N integers p1, p2, ..., pN (1 ≤ pi ≤ 106). The price of one share of stock on the i-th day is given by pi.

Print the maximum amount of money you can end up with at the end of N days.

NoteIn the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is  - 5 - 4 + 9 + 12 - 2 + 10 = 20.

object DD extends App {

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

  val Array(n) = readInts(1)
  val ps = readInts(n)

  var profit = 0L
  val pq = new java.util.PriorityQueue[Int]

  for (p <- ps) {
    pq.add(p)
    if (pq.peek < p) {
      profit += p - pq.poll()
      pq.add(p)
    }
  }

  println(profit)
}


You are given two integers $$$n$$$ and $$$m$$$. Calculate the number of pairs of arrays $$$(a, b)$$$ such that:  the length of both arrays is equal to $$$m$$$;  each element of each array is an integer between $$$1$$$ and $$$n$$$ (inclusive);  $$$a_i \le b_i$$$ for any index $$$i$$$ from $$$1$$$ to $$$m$$$;  array $$$a$$$ is sorted in non-descending order;  array $$$b$$$ is sorted in non-ascending order. As the result can be very large, you should print it modulo $$$10^9+7$$$.

The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 1000$$$, $$$1 \le m \le 10$$$).

Print one integer – the number of arrays $$$a$$$ and $$$b$$$ satisfying the conditions described above modulo $$$10^9+7$$$.

import java.io.BufferedInputStream
import java.util.Scanner

object Main extends App {
  val inputReader = new Scanner(new BufferedInputStream(System.in))
  val MOD = 1000000007L;
  val N = inputReader.nextInt()
  val M = inputReader.nextInt()
  val end_with = Array.ofDim[Long](N + 1, M + 1)
  val start_with = Array.ofDim[Long](N + 1, M + 1)
  for (k <- 1 to N) {
    end_with(k).update(1, 1)
    start_with(k).update(1, 1)
  }

  for (m <- 2 to M) {
    for (k <- 1 to N) {
      var sum = 0L;
      for (i <- 0 until k) {
        sum += end_with(k - i)(m - 1)
      }
      end_with(k).update(m, sum % MOD)
    }
  }

  for (m <- 2 to M) {
    for (k <- 1 to N) {
      var sum = 0L;
      for (i <- k to N) {
        sum += start_with(i)(m - 1)
      }
      start_with(k).update(m, sum % MOD)
    }
  }

  var result = 0L
  for (k <- 1 to N) {
    var start_at_least_k = 0L
    for (i <- k to N) {
      start_at_least_k += start_with(i)(M)
    }
    result = result + (end_with(k)(M) * (start_at_least_k % MOD)) % MOD
  }
  println(result % MOD)
}

import java.io.BufferedInputStream
import java.util.Scanner

object Main extends App {
  val inputReader = new Scanner(new BufferedInputStream(System.in))
  val MOD = 1000000007L;
  val N = inputReader.nextInt()
  val M = inputReader.nextInt()
  val end_with = Array.ofDim[Long](M + 1, N + 1)
  val start_with = Array.ofDim[Long](M + 1, N + 1)
  for (k <- 1 to N) {
    end_with(1).update(k, 1)
    start_with(1).update(k, 1)
  }

  for (m <- 2 to M) {
    for (k <- 1 to N) {
      val sum = end_with(m - 1).slice(1, k + 1).sum
      end_with(m).update(k, sum % MOD)
    }
  }

  for (m <- 2 to M) {
    for (k <- 1 to N) {
      val sum = start_with(m - 1).slice(k, N + 1).sum
      start_with(m).update(k, sum % MOD)
    }
  }

  var result = 0L
  for (k <- 1 to N) {
    val start_at_least_k = start_with(M).slice(k, N + 1).sum
    result = result + (end_with(M)(k) * (start_at_least_k % MOD)) % MOD
  }
  println(result % MOD)
}

object Main {
    def main(args: Array[String]) = {
      val Array(n, m) = readLine.split(" ").map(_.toInt)
      println(f1(n, m))
    }
    def f1(n: Int, m: Int): Long = {
        val a = Array.ofDim[Long](n + 1, m)
        for(j <- 0 to n) {
            a(j)(0) = 1
        }
        for (i <- 1 until m) {
            for (j <- 0 to n) {
                for (k <- 0 to j) {
                    a(j)(i) = (a(j)(i) + a(k)(i - 1)) % 1000000007L
                }
            }
        }
        val x = (for (
            i <- 1 to n;
            j <- 1 to n) yield (i, j)
        ).filter{ case (x, y) => x <= y }
        val s = x.foldLeft(0L){ case (s, (x, y)) =>
            (s + a(x - 1)(m-1) * a(n - y)(m-1)) % 1000000007L
        }
        s
    }
    def countSum(x: Int, m: Int) = {
        val a = Array.ofDim[Int](x + 1, m)
        for(j <- 1 to x) {
            a(j)(0) = 1
        }
        for (i <- 1 until m) {
            for (j <- 1 to x) {
                for (k <- 1 until j) {
                    a(j)(i) += a(k)(i - 1)
                }
            }
        }
        // println(a.map(_.mkString(" ")).mkString("\n"))
        val res = a(x)(m - 1)
        // println((x, m, res))
        res
    }
    def powL(x: Int, p: Int): Long = {
        if (p <= 0) 1L else (x.toLong * powL(x, p - 1)) % 1000000007L
    }
}

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

  val MOD = 1000000007
  val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
  val maxSize = n + 2 * m - 1
  val factorial = Array.fill(maxSize + 1){1L}
  val inv = Array.fill(maxSize + 1){1L}
  val invFactorial = Array.fill(maxSize + 1){1L}
  for (i ← 2 to maxSize) {
    factorial(i) = factorial(i - 1) * i % MOD
    inv(i) = (MOD - MOD / i) * inv(MOD % i) % MOD
    invFactorial(i) = inv(i) * invFactorial(i - 1) % MOD
  }
  println(
    factorial(maxSize) * invFactorial(n - 1) % MOD * invFactorial(2 * m) % MOD
  )
}


You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k > 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.

object A1253 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val Array(n) = readInts(1)
      val a = readInts(n)
      val b = readInts(n)
      for (i <- 0 until n)
        b(i) -= a(i)
      if (b.exists(_ < 0))
        out.println("NO")
      else if (b.forall(_ == 0))
        out.println("YES")
      else if (b.distinct.count(_ > 0) == 1) {
        var idxs = b.zipWithIndex.filter(_._1 != 0).map(_._2)
        if (idxs.length == (idxs.last - idxs.head + 1)) {
          out.println("YES")
        } else {
          out.println("NO")
        }
      } else {
        out.println("NO")
      }

      tests -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    val as, bs = nextInts(n)
    val l = (0 until n).indexWhere(i => as(i) != bs(i))
    val r = (0 until n).lastIndexWhere(i => as(i) != bs(i))
    val ok = if (l >= 0) {
      val d = bs(l) - as(l)
      d > 0 && (l to r).forall(i => bs(i) - as(i) == d)
    } else true

    out.println(if (ok) "YES" else "NO")
    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 A1253 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val Array(n) = readInts(1)
      val a = readInts(n)
      val b = readInts(n)
      for (i <- 0 until n)
        b(i) -= a(i)
      if (b.exists(_ < 0))
        out.println("NO")
      else {
        if (b.distinct.count(_ > 0) == 0)
          out.println("YES")
        else if (b.distinct.count(_ > 0) != 1)
          out.println("NO")
        else {
          var res = 0
          var i = 1
          var change = 0
          while (i < n) {
            if (b(i) != b(i - 1)) {
              change += 1
            }
            i += 1
          }
          if (change > 2)
            out.println("NO")
          else
            out.println("YES")
        }
      }

      tests -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}