You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .

The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤  109) — the elements of array a.

Print a single integer — the number of ways to split the array into three parts with the same sum.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val sum = data.sum
  val third = sum / 3
  if (sum % 3 == 0) {
    val r = data.foldLeft((0l, 0l, 0l)) {
      case((i, soFar, sumFromB), el) =>
        val nSum = sumFromB + el
        val nSoFar = if (nSum == 2 * third && third != 0) soFar + i
        else if (third == 0) Math.max(soFar, soFar + i - 1)
        else soFar
        val ni = if (nSum == third) i + 1 else i
        (ni, nSoFar, nSum)
    }
    println(r._2)
  } else {
    println(0)
  }

}

import java.util

import scala.collection.Searching

object C466 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readLongs(n)
    val sum = input.sum
    if(input.length < 3) {
      println("0")
    } else if(sum % 3 == 0) {
      val tofind = sum/3
      for(i <- 1 until n) {
        input(i) += input(i-1)
      }
      if (tofind == 0) {
        val x = input.count(_ == 0)
        println(((x-1).toLong*(x-2).toLong)/2L)
      } else {
        val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)
        val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)
        if(x.length == 0 || y.length == 0) {
          println("0")
        } else {
          var ret = 0L
          for(i <- x.indices) {
            ret += (y.length - y.indexWhere(_ > i))
          }
          println(ret)
        }
      }
    } else {
      println("0")
    }

  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/466/C"/>
 *
 * @author pvasilyev
 * @since 28 Apr 2016
 */
object Problem158 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  // sum(i) = sum(a, 0, i)
  val sum: Array[Long] = Array.ofDim[Long](n)
  sum(0) = a(0)
  for (i <- 1 until n) {
    sum(i) = sum(i - 1) + a(i)
  }
  if (sum(n - 1) % 3 != 0) {
    println(0)
  } else {
    val oneThirdOfSum = sum(n - 1) / 3
    // backSum(j) = sum(a, j, n - 1)
    val backSum: Array[Long] = Array.ofDim[Long](n)
    backSum(n - 1) = a(n - 1)
    for (i <- n - 2 to (0, -1)) {
      backSum(i) = backSum(i + 1) + a(i)
    }
    val cnt: Array[Int] = Array.ofDim(n)
    cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0
    for (i <- n - 2 to (0, -1)) {
      val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0
      cnt(i) = cnt(i+1) + tmp
    }

    var answer: Long = 0L
    for (i <- 1 until n-1) {
      if (sum(i-1) == oneThirdOfSum) {
        answer += cnt(i+1)
      }
    }

    println(answer)
  }
}

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

import scala.collection.mutable

object C466 {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Long](n)
    val prefixSum = new Array[Long](n)
    val map = new MultiHashSet[Long]
    a(0) = nextInt
    prefixSum(0) = a(0)
    for (i <- 1 until n) {
      a(i) = nextInt
      prefixSum(i) = a(i) + prefixSum(i - 1)
    }
    for (i <- 0 until n - 1) {
      map.add(prefixSum(i))
    }
    var ans = 0L
    for (pos <- 1 until n - 1) {
      val sum = prefixSum(pos - 1)
      map.remove(sum)
      val left = prefixSum(n - 1) - sum
      if (left / 2 == sum && left % 2 == 0) {
        val cnt = map.count(2 * sum)
        ans += cnt
      }
    }
    out.println(ans)
    return 0
  }
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toLong).toArray
    val total: Long= a.sum
    if(total % 3 != 0) println(0) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0L
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      }).toArray
      val t2Len = t2.length
      var last = 0
      var res = 0L
      t1.foreach(o => {
        val index = t2.indexWhere( _ > o, last)
        if(index != -1){
          last = index
          res += t2Len - index
        }
      })
      print(res)
    }
  }
  foo()
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val sum = data.sum
  if (sum % 3 == 0) {
    val agg = data.tail.scan(data.head){_+_}
    val firstCount = agg.count(_ == sum / 3)
    val secondCount = agg.count(_ == 2 * sum / 3)
    println(firstCount * secondCount)
  } else {
    println(0)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sum = data.sum
  val third = sum / 3
  if (sum % 3 == 0) {
    val r = data.foldLeft((0, 0l, 0l)) {
      case((i, soFar, sumFromB), el) =>
        val nSoFar = if (sumFromB + el == 2 * third && third != 0) soFar + i
        else if (third == 0) soFar + (i - 1) * i / 2
        else soFar
        val ni = if (sumFromB + el == third) i + 1 else i
        (ni, nSoFar, sumFromB + el)
    }
    println(r._2)
  } else {
    println(0)
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sum = data.sum
  val third = sum / 3
  if (sum % 3 == 0) {
    val r = data.foldLeft((0, 0l, 0l)) {
      case((i, soFar, sumFromB), el) =>
        val nSum = sumFromB + el
        val nSoFar = if (nSum == 2 * third && third != 0) soFar + i
        else if (third == 0) Math.max(soFar, soFar + i - 1)
        else soFar
        val ni = if (nSum == third) i + 1 else i
        (ni, nSoFar, nSum)
    }
    println(r._2)
  } else {
    println(0)
  }

}

import java.util

import scala.collection.Searching

object C466 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readLongs(n)
    val sum = input.sum
    if(input.size < 3) {
      println("0")
    } else if(sum%3 == 0) {
      val tofind = sum/3
      for(i <- 1 until n) {
        input(i) += input(i-1)
      }
      if (tofind == 0) {
        val x = input.count(_ == 0)
        println(((x-1).toLong*(x-2))/2.toLong)
      } else {
        val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)
        val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)
        if(x.length == 0 || y.length == 0) {
          println("0")
        } else {
          var ret = 0
          for(i <- x.indices) {
            ret += (y.length - y.indexWhere(_ > i))
          }
          println(ret)
        }
      }
    } else {
      println("0")
    }

  }
}

import java.util

import scala.collection.Searching

object C466 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readLongs(n)
    val sum = input.sum
    if(input.size < 3) {
      println("0")
    } else if(sum%3 == 0) {
      val tofind = sum/3
      for(i <- 1 until n) {
        input(i) += input(i-1)
      }
      val ret =
        if (tofind == 0) {
          val x = input.count(_ == 0)
          (x-1)*(x-2)/2
        } else {
          val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)
          val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)
          if(x.length == 0 || y.length == 0) {
            println("0")
          } else {
            var ret = 0
            for(i <- x.indices) {
              ret += (y.length - y.indexWhere(_ > i))
            }
            ret
          }
        }
      println(ret)
    } else {
      println("0")
    }

  }
}

import java.util

import scala.collection.Searching

object C466 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readLongs(n)
    val sum = input.sum
    if(input.size < 3) {
      println("0")
    } else if(sum%3 == 0) {
      val tofind = sum/3
      for(i <- 1 until n) {
        input(i) += input(i-1)
      }
      val ret =
        if (tofind == 0) {
          val x = input.count(_ == 0)
          x-2
        } else {
          val x = input.zipWithIndex.dropRight(2).filter(_._1 == tofind).map(_._2)
          val y = input.zipWithIndex.drop(1).dropRight(1).filter(_._1 == 2*tofind).map(_._2)
          if(x.length == 0 || y.length == 0) {
            println("0")
          } else {
            var ret = 0
            for(i <- x.indices) {
              ret += (y.length - y.indexWhere(_ > i))
            }
            ret
          }
        }
      println(ret)
    } else {
      println("0")
    }

  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/466/C"/>
 *
 * @author pvasilyev
 * @since 28 Apr 2016
 */
object Problem158 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  // sum(i) = sum(a, 0, i)
  val sum: Array[Long] = Array.ofDim[Long](n)
  sum(0) = a(0)
  for (i <- 1 until n) {
    sum(i) = sum(i - 1) + a(i)
  }
  if (sum(n - 1) % 3 != 0) {
    println(0)
  } else {
    val oneThirdOfSum = sum(n - 1) / 3
    // backSum(j) = sum(a, j, n - 1)
    val backSum: Array[Long] = Array.ofDim[Long](n)
    backSum(n - 1) = a(n - 1)
    for (i <- n - 2 to (0, -1)) {
      backSum(i) = backSum(i + 1) + a(i)
    }
    val cnt: Array[Int] = Array.ofDim(n)
    cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0
    for (i <- n - 2 to (0, -1)) {
      val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0
      cnt(i) = cnt(i+1) + tmp
    }

    var answer: Long = 0L
    for (i <- 0 until n-1) {
      if (sum(i) == oneThirdOfSum) {
        answer += cnt(i + 1)
      }
    }

    println(answer)
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/466/C"/>
 *
 * @author pvasilyev
 * @since 28 Apr 2016
 */
object Problem158 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  // sum(i) = sum(a, 0, i)
  val sum: Array[Long] = Array.ofDim(n)
  sum(0) = a(0)
  for (i <- 1 until n) {
    sum(i) = sum(i - 1) + a(i)
  }
  if (sum(n - 1) % 3 != 0) {
    println(0)
  } else {
    val oneThirdOfSum = sum(n - 1) / 3
    // backSum(j) = sum(a, j, n - 1)
    val backSum: Array[Long] = Array.ofDim(n)
    backSum(n - 1) = a(n - 1)
    for (i <- n - 2 to (0, -1)) {
      backSum(i) = backSum(i + 1) + a(i)
    }
    val cnt: Array[Int] = Array.ofDim(n)
    cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0
    for (i <- n - 2 to (0, -1)) {
      val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0
      cnt(i) = cnt(i+1) + tmp
    }

    var answer = 0
    for (i <- 1 until n-1) {
      if (sum(i) == oneThirdOfSum) {
        answer += cnt(i + 1)
      }
    }

    println(answer)
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/466/C"/>
 *
 * @author pvasilyev
 * @since 28 Apr 2016
 */
object Problem158 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  // sum(i) = sum(a, 0, i)
  val sum: Array[Long] = Array.ofDim[Long](n)
  sum(0) = a(0)
  for (i <- 1 until n) {
    sum(i) = sum(i - 1) + a(i)
  }
  if (sum(n - 1) % 3 != 0) {
    println(0)
  } else {
    val oneThirdOfSum = sum(n - 1) / 3
    // backSum(j) = sum(a, j, n - 1)
    val backSum: Array[Long] = Array.ofDim[Long](n)
    backSum(n - 1) = a(n - 1)
    for (i <- n - 2 to (0, -1)) {
      backSum(i) = backSum(i + 1) + a(i)
    }
    val cnt: Array[Int] = Array.ofDim(n)
    cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0
    for (i <- n - 2 to (0, -1)) {
      val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0
      cnt(i) = cnt(i+1) + tmp
    }

    var answer: Long = 0L
    for (i <- 1 until n-1) {
      if (sum(i) == oneThirdOfSum) {
        answer += cnt(i + 1)
      }
    }

    println(answer)
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/466/C"/>
 *
 * @author pvasilyev
 * @since 28 Apr 2016
 */
object Problem158 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  // sum(i) = sum(a, 0, i)
  val sum: Array[Long] = Array.ofDim(n)
  sum(0) = a(0)
  for (i <- 1 until n) {
    sum(i) = sum(i - 1) + a(i)
  }
  if (sum(n - 1) % 3 != 0) {
    println(0)
  } else {
    val oneThirdOfSum = sum(n - 1) / 3
    // backSum(j) = sum(a, j, n - 1)
    val backSum: Array[Long] = Array.ofDim(n)
    backSum(n - 1) = a(n - 1)
    for (i <- n - 2 to (0, -1)) {
      backSum(i) = backSum(i + 1) + a(i)
    }
    val cnt: Array[Int] = Array.ofDim(n)
    cnt(n - 1) = if (backSum(n - 1) == oneThirdOfSum) 1 else 0
    for (i <- n - 2 to (0, -1)) {
      val tmp = if (backSum(i) == oneThirdOfSum) 1 else 0
      cnt(i) = cnt(i+1) + tmp
    }

    var answer = 0
    for (i <- 1 until n-1) {
      if (sum(i) == oneThirdOfSum) {
        answer += cnt(i + 1)
      }
    }

    println(answer)
  }
}

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

import scala.collection.mutable

object C466 {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val prefixSum = new Array[Int](n)
    val map = new MultiHashSet[Int]
    a(0) = nextInt
    prefixSum(0) = a(0)
    for (i <- 1 until n) {
      a(i) = nextInt
      prefixSum(i) = a(i) + prefixSum(i - 1)
    }
    for (i <- 0 until n - 1) {
      map.add(prefixSum(i))
    }
    var ans = 0L
    for (pos <- 1 until n - 1) {
      val sum = prefixSum(pos - 1)
      map.remove(sum)
      val left = prefixSum(n - 1) - sum
      if (left / 2 == sum && left % 2 == 0) {
        val cnt = map.count(2 * sum)
        ans += cnt
      }
    }
    out.println(ans)
    return 0
  }
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    //val a = "1 -1 1 2 -1 -2 3 -3".split(" ").map(_.toInt)
    val total = a.sum
    if(total % 3 != 0) println(-1) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      })
      val t2Len = t2.length
      val res = t1.map(o => t2.indexWhere( _ > o)).filterNot(_ == -1).map(t2Len - _).sum
      print(res)
    }
  }
  foo()
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val total = a.sum
    if(total % 3 != 0) println(0) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      }).toArray
      val t2Len = t2.length
      var last = 0
      var res = 0L
      t1.foreach(o => {
        val index = t2.indexWhere( _ > o, last)
        if(index != -1){
          last = index
          res += t2Len - index
        }
      })
      print(res)
    }
  }
  foo()
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).toArray
    val total: Long= a.sum
    if(total % 3 != 0) println(0) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0L
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      }).toArray
      val t2Len = t2.length
      var last = 0
      var res = 0L
      t1.foreach(o => {
        val index = t2.indexWhere( _ > o, last)
        if(index != -1){
          last = index
          res += t2Len - index
        }
      })
      print(res)
    }
  }
  foo()
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).toArray
    val total = a.sum
    if(total % 3 != 0) println(0) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0L
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      }).toArray
      val t2Len = t2.length
      var last = 0
      var res = 0L
      t1.foreach(o => {
        val index = t2.indexWhere( _ > o, last)
        if(index != -1){
          last = index
          res += t2Len - index
        }
      })
      print(res)
    }
  }
  foo()
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    //val a = "1 -1 1 2 -1 -2 3 -3".split(" ").map(_.toInt)
    val total = a.sum
    if(total % 3 != 0) println(-1) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      })
      val t2Len = t2.length
      val res = t1.map(o => t2.indexWhere( _ > o)).filterNot(_ == -1).map(t2Len - _).foldLeft(0L)(_+_)
      print(res)
    }
  }
  foo()
}

object Solution extends App {
  def foo(): Unit = {
    val len = scala.io.StdIn.readInt()
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    //val a = "1 -1 1 2 -1 -2 3 -3".split(" ").map(_.toInt)
    val total = a.sum
    if(total % 3 != 0) println(0) else {
      val target = total / 3
      val target2 = target + target
      var sum = 0
      val t1 = (0 until len - 2).flatMap(i => {
        sum += a(i)
        if (sum == target) Some(i) else None
      })
      sum = 0
      val t2 = (0 until len - 1).flatMap(i => {
        sum += a(i)
        if (sum == target2) Some(i) else None
      })
      val t2Len = t2.length
      val res = t1.map(o => t2.indexWhere( _ > o)).filterNot(_ == -1).map(t2Len - _).sum
      print(res)
    }
  }
  foo()
}


You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu :  cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge.  It is guaranteed that the given graph has no self-loops or multiple edges.

Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.

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

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

  val n, m = sc.nextInt()
  val c = Array.tabulate(n)(_ => sc.nextInt())

  val mm = c.map(_ -> Set[Int]()).toMap

  for (i <- 0 until m) {
    val a, b = (sc.nextInt() - 1)
    if (c(a) != c(b)) {
      mm(c(a)) += c(b)
      mm(c(b)) += c(a)
    }
  }

  val (ans, _) = mm reduce { (a, b) =>
    if (b._2.size > a._2.size) b
    else if (b._2.size == a._2.size && b._1 < a._1) b else a
  }

  println(ans)
}

import java.util.Scanner

object Main extends App {
import scala.collection.mutable.{Map, Set}
  val sc = new Scanner(System.in)

  val n, m = sc.nextInt()
  val c = Array.tabulate(n)(_ => sc.nextInt())

  val mm = c.map(_ -> Set[Int]()).toMap

  for (i <- 0 until m) {
    val a, b = (sc.nextInt() - 1)
    if (c(a) != c(b)) {
      mm(c(a)) += c(b)
      mm(c(b)) += c(a)
    }
  }

  val (ans, _) = mm reduce { (a, b) =>
    if (b._2.size > a._2.size) b
    else if (b._2.size == a._2.size && b._1 < a._1) b else a
  }

  println(ans)
}

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

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

  val n, m = sc.nextInt()
  val c = Array.tabulate(n)(_ => sc.nextInt())

  val mm = Map[Int, Set[Int]]() withDefault (_ => Set[Int]())

  for (i <- 0 until m) {
    val a, b = (sc.nextInt() - 1)
    if (c(a) != c(b)) {
      mm(c(a)) = mm(c(a)) + c(b)
      mm(c(b)) = mm(c(b)) + c(a)
    }
  }

  val (ans, ansn) = mm.reduce((a, b) => if (b._2.size > a._2.size) b else a)

  println(ans)
}

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

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

  val n, m = sc.nextInt()
  val c = Array.tabulate(n)(_ => sc.nextInt())

  val mm = Map[Int, Int]() withDefault (_ => 0)

  for (i <- 0 until m) {
    val a, b = (sc.nextInt() - 1)
    if (c(a) != c(b)) {
      mm(c(a)) += 1
      mm(c(b)) += 1
    }
  }

  val (ans, ansn) = mm.reduce((a, b) => if (b._2 > a._2) b else a)

  println(ans)
}


You are given an array consisting of all integers from $$$[l, r]$$$ inclusive. For example, if $$$l = 2$$$ and $$$r = 5$$$, the array would be $$$[2, 3, 4, 5]$$$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 2 \cdot 10^5$$$) — the description of the array.

For each test case, output a single integer — the answer to the problem.

NoteIn the first test case, the array is $$$[1, 2]$$$. Currently, the bitwise AND is $$$0$$$, as $$$1\ \& \ 2 = 0$$$. However, after deleting $$$1$$$ (or $$$2$$$), the array becomes $$$[2]$$$ (or $$$[1]$$$), and the bitwise AND becomes $$$2$$$ (or $$$1$$$). This can be proven to be the optimal, so the answer is $$$1$$$.In the second test case, the array is $$$[2, 3, 4, 5, 6, 7, 8]$$$. Currently, the bitwise AND is $$$0$$$. However, after deleting $$$4$$$, $$$5$$$, and $$$8$$$, the array becomes $$$[2, 3, 6, 7]$$$, and the bitwise AND becomes $$$2$$$. This can be proven to be the optimal, so the answer is $$$3$$$. Note that there may be other ways to delete $$$3$$$ elements.

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

import java.io._
import java.util.StringTokenizer
import scala.math.{max, min, pow}
import scala.reflect.ClassTag
import scala.collection.immutable._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

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

  import Main._
  import fScanner._

  val M: Int = 200012
  val L: Int = 20

  def pre(mx: Int, L: Int): mutable.Seq[ArrayBuffer[Int]] = {
    val prf = ArrayBuffer.fill(M, 20)(0)
    (1 until mx).foreach{ i =>
      (0 until L).foreach { j =>
        prf(i)(j) =
          prf(i-1)(j) + {
            if (((1 << j) & i) > 0) 1
            else 0
          }
      }
    }
    prf
  }

  def solve(): Unit = {
    val prf = pre(M, L)
    val T = ni()

    (1 to T).foreach { tc =>
      val L = ni()
      val R = ni()
      val ans =
        (0 until 20).map{ j =>
          R - L + 1 - {
            val x = prf(R)(j) - prf(L-1)(j)
            x
          }
        }.min
      out.println(ans)
    }
  }

}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

import java.io._
import java.util.StringTokenizer
import scala.math.{max, min, pow}
import scala.reflect.ClassTag
import scala.collection.immutable._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

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

  import Main._
  import fScanner._

  val M: Int = 200012
  val L: Int = 20

  def pre(mx: Int, L: Int): mutable.Seq[ArrayBuffer[Int]] = {
    val prf = ArrayBuffer.fill(M, 20)(0)
    (1 until mx).foreach{ i =>
      (0 until L).foreach { j =>
        prf(i)(j) =
          prf(i-1)(j) + {
            if (((1 << j) & i) > 0) 1
            else 0
          }
      }
    }
    prf
  }

  def solve(): Unit = {
    val prf = pre(M, L)
    val T = ni()

    (1 to T).foreach { tc =>
      val L = ni()
      val R = ni()
      val ans =
        (0 until 20).map{ j =>
          R - L + 1 - {
            val x = prf(R)(j) - prf(L-1)(j)
            x
          }
        }.min
      out.println(ans)
    }
  }

}


Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is .Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≤ ai ≤ n).

Print a single integer — the minimum number of pages Ryouko needs to turn.

NoteIn the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3.In the second sample, optimal solution is achieved by merging page 9 to 4.

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

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, ArrayBuffer[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> ArrayBuffer.empty[Int]
      left(r) += l
      if (!left.contains(l)) left += l -> ArrayBuffer.empty[Int]
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).sorted
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable()
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable()
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a)()
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

class Growable(private var arr: Array[Int] = Array.empty[Int]) {
  var size = arr.size
  @inline def apply(index: Int): Int = arr(index)
  @inline def +=(x: Int): Unit = {
    if (size == arr.size) {
      val bigger = Array.ofDim[Int](2 * size + 1)
      arr.copyToArray(bigger)
      arr = bigger
    }
    arr(size) = x
    size += 1
  }
  @inline def apply() = arr.take(size)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a)()
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

class Growable[T](private var arr: Array[T]) {
  var size = arr.size
  def apply(index: Int): T = arr(index)
  def +=(x: T)(implicit t: ClassTag[T]): Unit = {
    if (size == arr.size) {
      val bigger = Array.ofDim[T](2 * size + 1)
      arr.copyToArray(bigger)
      arr = bigger
    }
    arr(size) = x
    size += 1
  }
  def apply() = arr.take(size)
}

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

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, ArrayBuffer[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> ArrayBuffer.empty[Int]
      left(r) += l
      if (!left.contains(l)) left += l -> ArrayBuffer.empty[Int]
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).toArray//.sorted
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.collection.mutable.ArrayBuilder
import java.util.Arrays

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val neighbours = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!neighbours.contains(r)) neighbours += r -> new ArrayBuilder.ofInt
      neighbours(r) += l
      if (!neighbours.contains(l)) neighbours += l -> new ArrayBuilder.ofInt
      neighbours(l) += r
    }
  }

  for (a <- neighbours.keys) {
    val sorted = neighbours(a).result
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (x <- sorted) {
      news += math.abs(x - med)
      old += math.abs(x - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a)()
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

class Growable[T](private var arr: Array[T]) {
  var size = arr.size
  @inline def apply(index: Int): T = arr(index)
  @inline def +=(x: T)(implicit t: ClassTag[T]): Unit = {
    if (size == arr.size) {
      val bigger = Array.ofDim[T](2 * size + 1)
      arr.copyToArray(bigger)
      arr = bigger
    }
    arr(size) = x
    size += 1
  }
  @inline def apply() = arr.take(size)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable()
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable()
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).get
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)

  type Nums = Int
  class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {
    var size = arr.size
    @inline def apply(index: Int): Nums = arr(index)
    @inline def +=(x: Nums): Unit = {
      if (size == arr.size) {
        val bigger = Array.ofDim[Int](2 * size + 1)
        arr.copyToArray(bigger)
        arr = bigger
      }
      arr(size) = x
      size += 1
    }
    @inline def get = arr.view(0, size).toArray
  }
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a)()
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

@specialized(Int)
class Growable[T](private var arr: Array[T]) {
  var size = arr.size
  @inline def apply(index: Int): T = arr(index)
  @inline def +=(x: T)(implicit t: ClassTag[T]): Unit = {
    if (size == arr.size) {
      val bigger = Array.ofDim[T](2 * size + 1)
      arr.copyToArray(bigger)
      arr = bigger
    }
    arr(size) = x
    size += 1
  }
  @inline def apply() = arr.take(size)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.collection.mutable.ArrayBuilder

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val neighbours = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!neighbours.contains(r)) neighbours += r -> new ArrayBuilder.ofInt
      neighbours(r) += l
      if (!neighbours.contains(l)) neighbours += l -> new ArrayBuilder.ofInt
      neighbours(l) += r
    }
  }

  for (a <- neighbours.keys) {
    val sorted = neighbours(a).result.sorted
    //Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (x <- sorted) {
      news += math.abs(x - med)
      old += math.abs(x - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.collection.mutable.ArrayBuilder
import java.util.Arrays

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val neighbours = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!neighbours.contains(r)) neighbours += r -> new ArrayBuilder.ofInt
      neighbours(r) += l
      if (!neighbours.contains(l)) neighbours += l -> new ArrayBuilder.ofInt
      neighbours(l) += r
    }
  }

  for (a <- neighbours.keys) {
    val sorted = neighbours(a).result
    //Sorting.quickSort(sorted)
    Arrays.sort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (x <- sorted) {
      news += math.abs(x - med)
      old += math.abs(x - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable()
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable()
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).get
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)

  type Nums = Int
  class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {
    var size = arr.size
    @inline def apply(index: Int): Nums = arr(index)
    @inline def +=(x: Nums): Unit = {
      if (size == arr.size) {
        val bigger = Array.ofDim[Int](2 * size + 1)
        arr.copyToArray(bigger)
        arr = bigger
      }
      arr(size) = x
      size += 1
    }
    @inline def get = arr.take(size)
  }
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable()
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable()
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a)()
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

class Growable(private var arr: Array[Int] = Array.empty[Int]) {
  var size = arr.size
  @inline def apply(index: Int) = arr(index)
  @inline def +=(x: Int): Unit = {
    if (size == arr.size) {
      val bigger = Array.ofDim[Int](2 * size + 1)
      arr.copyToArray(bigger)
      arr = bigger
    }
    arr(size) = x
    size += 1
  }
  @inline def apply() = arr.take(size)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.collection.mutable.ArrayBuilder

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, ArrayBuilder[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new ArrayBuilder.ofInt
      left(r) += l
      if (!left.contains(l)) left += l -> new ArrayBuilder.ofInt
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).result
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)

  type Nums = Int
  class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {
    var size = arr.size
    @inline def apply(index: Int): Nums = arr(index)
    @inline def +=(x: Nums): Unit = {
      if (size == arr.size) {
        val bigger = Array.ofDim[Int](2 * size + 1)
        arr.copyToArray(bigger)
        arr = bigger
      }
      arr(size) = x
      size += 1
    }
    @inline def get = {
      val newelems = new Array[Nums](size)
      if (this.size > 0) Array.copy(arr, 0, newelems, 0, size)
      newelems
    }
  }
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable()
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable()
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).get
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)

  type Nums = Int
  class Growable(private var arr: Array[Nums] = Array.empty[Nums]) {
    var size = arr.size
    @inline def apply(index: Int): Nums = arr(index)
    @inline def +=(x: Nums): Unit = {
      if (size == arr.size) {
        val bigger = Array.ofDim[Int](2 * size + 1)
        arr.copyToArray(bigger)
        arr = bigger
      }
      arr(size) = x
      size += 1
    }
    @inline def get = {
      val newelems = new Array[Nums](size)
      if (this.size > 0) Array.copy(arr, 0, newelems, 0, size)
      newelems
    }
  }
}

/**
 * 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, m) = readInts(2)

  val as = readLongs(m)

  var moves = 0L
  var canSave1 = 0L
  var canSave2 = 0L
  var canSave3 = 0L

  if (m > 1) {
    canSave2 = math.abs(as(0) - as(1))
    canSave3 = math.abs(as(m - 1) - as(m - 2))
  }

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    if (i < m - 1) {
      val save1 = math.abs(as(i) - as(i - 1)) + math.abs(as(i) - as(i + 1)) - math.abs(as(i + 1) - as(i - 1))
      if (save1 > canSave1) canSave1 = save1
    }
  }

  println(moves - (canSave1 max canSave2 max canSave3))
}

/**
 * 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, m) = readInts(2)

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = mutable.Map.empty[Int, Map[Int, Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (left.contains(r)) {
      left(r) += (l -> (left(r)(l) + 1))
    } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))
    if (left.contains(l)) {
      left(l) += (r -> (left(l)(r) + 1))
    } else left += (l -> mutable.Map(r -> 1).withDefaultValue(0))
    cnt(l) += 1
    cnt(r) += 1
  }

  for (a <- as.distinct) {
    if (left.contains(a)) {
      val middle = (cnt(a) - 1) / 2
      var sum = 0L
      var med = 0L
      //var i = 0
      var neighbours = left(a).toSeq.sortBy(_._1)
      while (sum <= middle) {
        med = neighbours.head._1
        sum += neighbours.head._2
        //i += 1
        neighbours = neighbours.tail
      }
      //println(middle, sum)
      var news = 0L
      var old = 0L
      for (l <- left(a).keys) {
        news += math.abs(l - med) * left(a)(l)
        old += math.abs(l - a) * left(a)(l)
      }
      val save = math.abs(news - old)
      if (save > canSave1) canSave1 = save
    }
  }

  println(moves - canSave1)
}

/**
 * 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, m) = readInts(2)

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L
  var canSave2 = 0L
  var canSave3 = 0L

  val left = mutable.Map.empty[Int, Map[Int, Int]]
  val right = mutable.Map.empty[Int, Map[Int, Int]]

  if (m > 1) {
    canSave2 = math.abs(as(0) - as(1))
    canSave3 = math.abs(as(m - 1) - as(m - 2))
  }

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (right.contains(l)) {
      right(l) += (r -> (right(l)(r) + 1))
    } else right += (l -> mutable.Map(r -> 1).withDefaultValue(0))
    if (left.contains(r)) {
      left(r) += (l -> (left(r)(l) + 1))
    } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))
  }

  for (a <- as) {
    val neighbours = mutable.ArrayBuffer[Int]()
    if (right.contains(a)) for (r <- right(a).keys) {
      for (cnt <- 1 to right(a)(r)) neighbours += r
    }
    if (left.contains(a)) for (l <- left(a).keys) {
      for (cnt <- 1 to left(a)(l)) neighbours += l
    }
    if (neighbours.nonEmpty) {
      val sorted = neighbours.sorted
      val med: Long = sorted((sorted.size - 1) / 2)
      val news = neighbours.map(x => math.abs(x - med)).sum
      val old = neighbours.map(x => math.abs(a - med)).sum
     // println(a, news, old)
      val save = math.abs(news - old)
      if (save > canSave1) canSave1 = save
    }
  }

  println(moves - canSave1)
}

/**
 * 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, m) = readInts(2)

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = mutable.Map.empty[Int, Map[Int, Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (left.contains(r)) {
      left(r) += (l -> (left(r)(l) + 1))
    } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))
    if (left.contains(l)) {
      left(l) += (r -> (left(l)(r) + 1))
    } else left += (l -> mutable.Map(r -> 1).withDefaultValue(0))
    cnt(l) += 1
    cnt(r) += 1
  }

  for (a <- as.distinct) {
    if (left.contains(a)) {
      val middle = (cnt(a) - 1) / 2
      var sum = 0
      var med = 0
      //var i = 0
      var neighbours = left(a).toSeq.sortBy(_._1)
      while (sum <= middle) {
        med = neighbours.head._1
        sum += neighbours.head._2
        //i += 1
        neighbours = neighbours.tail
      }
      //println(middle, sum)
      var news = 0L
      var old = 0L
      for (l <- left(a).keys) {
        val mult = left(a)(l).toLong
        news += math.abs(l - med) * mult
        old += math.abs(l - a) * mult
      }
      val save = math.abs(news - old)
      if (save > canSave1) canSave1 = save
    }
  }

  println(moves - canSave1)
}

/**
 * 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, m) = readInts(2)

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L
  var canSave2 = 0L
  var canSave3 = 0L

  val left = mutable.Map.empty[Int, Map[Int, Int]]
  val right = mutable.Map.empty[Int, Map[Int, Int]]
  var cnt = Array.fill(n + 1)(0)

  if (m > 1) {
    canSave2 = math.abs(as(0) - as(1))
    canSave3 = math.abs(as(m - 1) - as(m - 2))
  }

  cnt(as(0)) += 1
  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (right.contains(l)) {
      right(l) += (r -> (right(l)(r) + 1))
    } else right += (l -> mutable.Map(r -> 1).withDefaultValue(0))
    if (left.contains(r)) {
      left(r) += (l -> (left(r)(l) + 1))
    } else left += (r -> mutable.Map(l -> 1).withDefaultValue(0))
    //cnt(as(i)) += 1
  }

  for (a <- as.distinct) {
    //val neighbours = new mutable.ArrayBuffer[Int](2 * cnt(a))
    var sum = 0L
    var count = 0
    if (right.contains(a)) for (r <- right(a).keys) {
      //for (cnt <- 1 to right(a)(r)) neighbours += r
      sum += r * right(a)(r)
      count += right(a)(r)
    }
    if (left.contains(a)) for (l <- left(a).keys) {
      //for (cnt <- 1 to left(a)(l)) neighbours += l
      sum += l * left(a)(l)
      count += left(a)(l)
    }
    if (count > 0) {
      //val sorted = neighbours.sorted
      //val med = sorted((sorted.size - 1) / 2)
      //val med: Long = neighbours.sum / neighbours.size
      val med: Long = sum / count
      var news = 0L
      var old = 0L
      if (right.contains(a)) for (r <- right(a).keys) {
        news += math.abs(r - med) * right(a)(r)
        old += math.abs(r - a) * right(a)(r)
      }
      if (left.contains(a)) for (l <- left(a).keys) {
        news += math.abs(l - med) * left(a)(l)
        old += math.abs(l - a) * left(a)(l)
      }
       /*     for (x <- neighbours) {
              news += math.abs(x - med)
              old += math.abs(x - a)
            }*/
      //println(a, med, news, old)
      val save = math.abs(news - old)
      if (save > canSave1) canSave1 = save
    }
  }

  println(moves - canSave1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.util.Sorting
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object A extends App {

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

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

  val as = readInts(m)

  var moves = 0L
  var canSave1 = 0L

  val left = scala.collection.mutable.Map.empty[Int, Growable[Int]]
  var cnt = Array.fill(n + 1)(0)

  for (i <- 1 until m) {
    moves += math.abs(as(i) - as(i - 1))
    val l = as(i - 1)
    val r = as(i)
    if (l != r) {
      if (!left.contains(r)) left += r -> new Growable[Int](Array.empty)
      left(r) += l
      if (!left.contains(l)) left += l -> new Growable[Int](Array.empty)
      left(l) += r
    }
  }

  for (a <- left.keys) {
    val sorted = left(a).arr
    Sorting.quickSort(sorted)
    val middle = (sorted.size - 1) / 2
    val med = sorted(middle)
    var news = 0L
    var old = 0L
    for (l <- sorted) {
      news += math.abs(l - med)
      old += math.abs(l - a)
    }
    //println(med, old, news)
    val save = math.abs(news - old)
    if (save > canSave1) canSave1 = save
  }

  println(moves - canSave1)
}

class Growable[T](var arr: Array[T]) {
  var size = arr.size
  def apply(index: Int): T = arr(index)
  def +=(x: T)(implicit t: ClassTag[T]): Unit = {
    if (size == arr.size) {
      val bigger = Array.ofDim[T](2 * size + 1)
      arr.copyToArray(bigger)
      arr = bigger
    }
    arr(size) = x
    size += 1
  }
}


Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.  The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

NotePlease note that Dima got a good old kick in the pants for the second sample from the statement.

object Main {
  def main(args: Array[String]) {
    val n=readLine().toInt
    var s:StringBuilder=new StringBuilder()
    s++="<3"
    for (i<-1 to n)
      s++=readLine()++="<3"
    val r=readLine()
    var j=0
    for (i<-0 until r.length)
      if (j!=s.length && s(j)==r(i))
        j+=1
   // println(s.length + " "+j)
    println(if (s.length==j) "yes" else "no")
  }
}

object Main {
  def main(args: Array[String]) {
    val n=readLine().toInt
    var s:StringBuilder=new StringBuilder()
    s++="<3"
    for (i<-1 to n)
      s++=readLine()++="<3"
    val r=readLine()
    var j=0
    for (i<-0 until r.length)
      if (j!=s.length && s(j)==r(i))
        j+=1
   // println(s.length + " "+j)
    println(if (s.length<=j) "yes" else "no")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = ("" :: (1 to n).map(_ => in.next()).toList).map(_ + "<3")

  val res = in.next().foldLeft(data.head.toList, data.tail) {
    case ((x::xs, left), ch) if x == ch =>
      if (xs.isEmpty && left.isEmpty)
        (Nil, left)
      else if (xs.isEmpty)
        (left.head.toList, left.tail)
      else (xs, left)
    case (acc, el) => acc
  }

  if (res._1.isEmpty && res._2.isEmpty)
    println("yes")
  else
    println("no")
}

import scala.collection._

object B extends App {

  val n = readInt
  val sb = new StringBuilder("<3")

  for (i <- 1 to n) {
    sb.append(readLine)
    sb.append("<3")
  }
  val text = sb.toString

  val sms = readLine

  var i, j = 0
  while (i < text.length && j < sms.length) {
    if (text(i) == sms(j)) i += 1
    j += 1
  }

  println(if (i == text.length) "yes" else "no")
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield(readLine())
    val e = a.mkString("<3", "<3", "<3")
    var i = 0
    for(c <- readLine()) {
      if(i != e.size && c == e(i)) i += 1
    }
    if (i == e.size) println("yes")
    else println("no")
  }
}

import java.util.Scanner

/**	#208
 * 	B. Dima and Text Messages
 */

object DimaandTextMessages extends App {
  val cin = new Scanner(System.in)

  val inMessage = new StringBuilder
  inMessage.append("<3")

  val n = cin.nextInt
  (0 until n).foreach(i => inMessage.append(cin.next).append("<3"))

  val message = inMessage.toString
  val encodedMessage = cin.next

  var index = 0
  (0 until encodedMessage.length).foreach { i =>
    if (index + 1 <= message.length && message(index) == encodedMessage(i))
      index += 1
  }

  println(if (index == message.length) "yes" else "no")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = ("" :: (1 to n).map(_ => in.next()).toList).map(_ + "<3")

  val res = in.next().foldLeft(data.head.toList, data.tail) {
    case ((x::xs, left), ch) if x == ch =>
      if (xs.isEmpty && left.isEmpty)
        (Nil, left)
      else if (xs.isEmpty)
        (left.head.toList, left.tail)
      else (xs, left)
    case (acc, el) => acc
  }

  if (res._1.isEmpty && res._2.isEmpty)
    println("YES")
  else
    println("NO")
}

import scala.collection._

object B extends App {

  val n = readInt
  val sb = new StringBuilder("<3")

  for (i <- 1 to n) sb.append(readLine)
  val text = sb.toString

  val sms = readLine

  var i, j = 0
  while (i < text.length && j < sms.length) {
    if (text(i) == sms(j)) i += 1
    j += 1
  }

  println(if (i == text.length) "yes" else "no")
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield(readLine())
    val e = a.mkString("<3", "<3", "<3")
    var i = 0
    for(c <- readLine()) {
      if(i != e.size || c == e(i)) i += 0
    }
    if (i == e.size) println("yes")
    else println("no")
  }
}

import java.util.Scanner

/**	#208
 * 	B. Dima and Text Messages
 */

object DimaandTextMessages extends App {
  val cin = new Scanner(System.in)

  val inMessage = new StringBuilder
  inMessage.append("<3")

  val n = cin.nextInt
  (0 until n).foreach(i => inMessage.append(cin.nextLine).append("<3"))

  val message = inMessage.toString
  val encodedMessage = cin.next

  var index = 0
  (0 until encodedMessage.length).foreach { i =>
    if (index + 1 < message.length && message(index) == encodedMessage(i))
      index += 1
  }

  println(if (index == message.length) "yes" else "no")
}

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

object Solver extends App {
  val cin = new Scanner(System.in)

  val n = cin.nextInt

  val wordsBuffer = ArrayBuffer[String]()
  for (i <- 0 until n) wordsBuffer += cin.next

  val words = wordsBuffer.toSeq
  val message = cin.next.replaceAll("[012456789]", "").replaceAll(">", "").replaceAll("<3", " ").trim

  var ok = true
  for (i <- 0 until message.length - 1)
    if (message(i) == ' ' && message(i + 1) == ' ')
      ok = false

  val messageWords = message.split(" ").toSeq
  ok &= messageWords.length == n

  if (!ok) {
    println("no")
    exit(0)
  }

  val both = words.zip(messageWords)
  ok &= both.forall(pair => pair._1 == pair._2)

  println(if (ok) "yes" else "no")
}


Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are $$$2$$$ teams each having $$$n$$$ players and $$$2n$$$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the $$$i$$$-th of the heroes as $$$p_i$$$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $$$m$$$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $$$q$$$ or greater regardless of jury's program choices, you must get $$$q$$$ or greater to pass a test.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^3$$$, $$$0 \le m \le n$$$) — the number of players in one team and the number of special pairs of heroes. The second line contains $$$2n$$$ integers $$$p_1, p_2, \ldots, p_{2n}$$$ ($$$1 \le p_i \le 10^3$$$) — the powers of the heroes. Each of the next $$$m$$$ lines contains two integer $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 2n$$$, $$$a \ne b$$$) — a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list. The next line contains a single integer $$$t$$$ ($$$1 \le t \le 2$$$) — the team you are to play for. If $$$t = 1$$$, the first turn is yours, otherwise you have the second turn. Hacks In order to hack, use the format described above with one additional line. In this line output $$$2n$$$ distinct integers from $$$1$$$ to $$$2n$$$ — the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.

NoteIn the first example the first turn is yours. In example, you choose $$$6$$$, the other team is forced to reply with $$$2$$$. You choose $$$5$$$, the other team chooses $$$4$$$. Finally, you choose $$$3$$$ and the other team choose $$$1$$$.In the second example you have the second turn. The other team chooses $$$6$$$, you choose $$$5$$$, forcing the other team to choose $$$1$$$. Now you choose $$$4$$$, the other team chooses $$$3$$$ and you choose $$$2$$$.

object C extends App {

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

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

  val pairs = Array.fill(m) {
    readInts(2).map(_ - 1).sortBy(ps)
  }

  val Array(t0) = readInts(1)
  var myTurn = t0 == 1

  var left = 2 * n
  var next = -1
  while (left > 0) {
    if (myTurn) {
      if (next == -1) {
        var maxPair = 0
        for (i <- 0 until m) {
          val p = ps(pairs(i)(1))
          if (p > maxPair) {
            next = pairs(i)(1)
            maxPair = p
          }
        }
        if (next == -1) {
          var max = 0
          for (i <- 0 until 2 * n) {
            if (ps(i) > max) {
              next = i
              max = ps(i)
            }
          }
        }
      }
      ps(next) = -1
      println(next + 1)
    } else {
      val Array(x0) = readInts(1)
      val x = x0 - 1
      ps(x) = -1
      next = -1
      var i = 0
      while (i < m && next == -1) {
        if (pairs(i)(0) == x && ps(pairs(i)(1)) > 0) {
          next = pairs(i)(1)
        } else if (pairs(i)(1) == x && ps(pairs(i)(0)) > 0) {
          next = pairs(i)(0)
        }
        i += 1
      }
    }
    myTurn = !myTurn
    left -= 1
  }

}

object C extends App {

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

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

  val pairs = Array.fill(m) {
    readInts(2).map(_ - 1).sortBy(ps)
  }

  val Array(t0) = readInts(1)
  var myTurn = t0 == 1

  var left = 2 * n
  var next = -1
  while (left > 0) {
    if (myTurn) {
      if (next >= 0) {
        println(next + 1)
      } else {
        var maxPair = 0
        for (i <- 0 until m) {
          val p = ps(pairs(i)(1))
          if (p > maxPair) {
            next = pairs(i)(1)
            maxPair = p
          }
        }
        if (next == -1) {
          var max = 0
          for (i <- 0 until 2 * n) {
            if (ps(i) > max) {
              next = i
              max = ps(i)
            }
          }
        }
        ps(next) = -1
        println(next + 1)
      }
    } else {
      val Array(x0) = readInts(1)
      val x = x0 - 1
      ps(x) = -1
      next = -1
      var i = 0
      while (i < m && next == -1) {
        if (pairs(i)(0) == x && ps(pairs(i)(1)) > 0) {
          next = pairs(i)(1)
        } else if (pairs(i)(1) == x && ps(pairs(i)(0)) > 0) {
          next = pairs(i)(0)
        }
        i += 1
      }
    }
    myTurn = !myTurn
    left -= 1
  }

}


This is the easier version of the problem. In this version $$$1 \le n, m \le 100$$$. You can hack this problem only if you solve and lock both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$:  $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list);  $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if:  it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$;  and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t<c_t$$$. For example:  $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$,  $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$,  $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.

Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.

import scala.math._, scala.collection._, scala.io.StdIn._

object D2 extends App {
  val n = readInt
  val a = readInts
  val m = readInt

  val top = a.zipWithIndex sortBy { case (x,i) => (-x,i) }

  val r = top.scanLeft(SortedSet.empty[Int]) {
    case (r, (x,i)) => r + i
  }

  for (_ <- 1 to m) {
    val Array(k,pos) = readInts
    println(a(r(k).slice(pos-1,pos).firstKey))
  }

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

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  case class Entry(a: Int, i: Int)
  case class Query(k: Int, pos: Int, m: Int)

  class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {
  def this(n: Int) = this(n, 0)(_ + _)

  private val N = {
    val a = Integer.highestOneBit(n)
    if (a == n) a else a << 1
  }
  private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)

  /**
    * 1 index
    * addとindex違うよ
    * cumsumなんかといっしょ
    */
  def sum(i: Int): Int = {
    assert(i <= n)
    var x = i
    var s: Int = zero
    while(x > 0) {
      s = f(s, bit(x))
      x -= x & -x
    }
    s
  }

  /**
    * 0 index
    */
  def add(i: Int, a: Int): Unit = {
    assert(i < n)
    var x = i + 1
    while(x <= N) {
      bit(x) = f(bit(x), a)
      x += x & -x
    }
  }

  def sumAll: Int = sum(n)

  // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
  private def sub(a: Int, b: Int) = a - b
  private def lt(a: Int, b: Int) = a < b

  /**
    * [l, r)
    */
  def query(l: Int, r: Int): Int = {
    assert(r > l)
    sub(sum(r), sum(l))
  }

  def lowerBound(W: Int): Int = {
    var k = N
    var x = 0
    var w = W
    while(k > 0) {
      if (x + k <= N && lt(bit(x + k), w)) {
        w = sub(w, bit(x + k))
        x += k
      }
      k /= 2
    }
    math.min(n, x)
  }
}
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val A = na(N)
    val E = Array.ofDim[Entry](N)
    REP(N) { i =>
      E(i) = Entry(A(i), i)
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = {
        if (o1.a == o2.a) Integer.compare(o1.i, o2.i)
        else Integer.compare(o2.a, o1.a) // 降順
      }
    })
    val M = ni()
    val queried = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())
    val ans = Array.ofDim[Int](M)
    REP(M) { m =>
      val k, pos = ni()
      val q = Query(k, pos, m)
      queried(k - 1) += q
    }

    val bit = new BIT(N)
    REP(N) { i =>
      bit.add(E(i).i, 1)
      queried(i).foreach { q =>
        val ix = bit.lowerBound(q.pos)
        ans(q.m) = A(ix)
      }
    }

    REP(M) { i =>
      out.println(ans(i))
    }
  }
}

import scala.collection.mutable.ArrayBuffer

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

  val n = nextInt
  val as = nextInts(n)
  val sorted = as.zipWithIndex.sortBy {
    case (x, i) => (x, -i)
  }
  val order = Array.ofDim[Int](n)
  for (i <- as.indices) {
    order(sorted(i)._2) = i
  }

  val m = nextInt
  val res = new ArrayBuffer[Int]
  for (q <- 1 to m) {
    var k, pos = nextInt
    var i = 0
    while (pos > 0) {
      if (order(i) + k >= n) {
        pos -= 1
        if (pos == 0) res += as(i)
      }
      i += 1
    }
  }

  out.println(res.mkString("\n"))
  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
  }
}


Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:  Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li ≤ j ≤ ri.  Find the maximum of elements from li to ri. That is, calculate the value . Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.

The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly. Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 ≤ ti ≤ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 ≤ li ≤ ri ≤ n,  - 104 ≤ di ≤ 104) — the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 ≤ li ≤ ri ≤ n,  - 5·107 ≤ mi ≤ 5·107) — the description of the operation of the second type. The operations are given in the order Levko performed them on his array.

In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise. If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| ≤ 109) — the recovered array.

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, m) = readInts(2)
  val ds = Array.fill(n)(0)
  val as = Array.fill(n)(1000000000)

  val ops = Array.fill(m)(readInts(4))

  for (j <- 0 until m) {
    val Array(t, l, r, x) = ops(j)
    if (t == 1) {
      var i = l - 1
      while (i < r) {
        ds(i) += x
        i += 1
      }
    } else {
      var i = l - 1
      var found = false
      while (i < r) {
        if (as(i) >= x - ds(i)) found = true
        as(i) = math.min(x - ds(i), as(i))
        i += 1
      }
      if (!found) {
        println("NO")
        exit
      }
    }
  }

  val ans = as.clone

  for (j <- 0 until m) {
    val Array(t, l, r, x) = ops(j)
    if (t == 1) {
      var i = l - 1
      while (i < r) {
        as(i) += x
        i += 1
      }
    } else {
      if (x != as.view(l - 1, r).max) {
        println("NO")
        exit
      }
    }
  }

  println("YES")
  println(ans.mkString(" "))
}

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, m) = readInts(2)
  val ds = Array.fill(n)(0)
  val maxs = Array.fill(n)(1000000000)

  for (j <- 0 until m) {
    val Array(t, l, r, x) = readInts(4)
    if (t == 1) {
      var i = l - 1
      while (i < r) {
        ds(i) += x
        i += 1
      }
    } else {
      var i = l - 1
      var found = false
      while (i < r) {
        if (maxs(i) >= x - ds(i)) {
          found = true
          maxs(i) = math.min(x - ds(i), maxs(i))
          //ds(i) = 0
        } else {
          maxs(i) = math.min(x - ds(i), maxs(i))
          //maxs(i) -= ds(i)
          //ds(i) = 0
        }
        i += 1
      }
      if (!found) {
        //println(j, i, maxs(i), ds(i), x)
        println("NO")
        exit
      }
    }
  }

  println("YES")
  println(maxs.mkString(" "))
}