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

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

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

  }
}

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

}

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


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


/**
 * 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).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.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.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
  }
}


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

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


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


import scala.io.StdIn._
import scala.collection.immutable._
import scala.annotation.tailrec
object test{
    def main(args: Array[String]): Unit = {
        var t = readInt

        while(t > 0) {
            val m = readLine.split(" ").map(_.toInt).toList
            if(m(0).min(m(1)) > m(2).max(m(3)) || m(2).min(m(3)) > m(0).max(m(1)))
                println("NO")
            else
                println("YES")

            t -= 1
        }
    }
}

import scala.io.StdIn._

object A extends App {
  for (_ <- 0 until readInt) {
    val s @ Array(s1, s2, s3, s4) = readLine.split(" ").map(_.toInt)
    if (s.sortBy(-_).take(2).toSet == Set(s1.max(s2), s3.max(s4)))
      println("YES")
    else
      println("NO")
  }
}


import scala.collection.mutable

object A 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) = readInts(1)
  val as = readInts(n)
  val xs = Array.fill(n)(false)

  var i = 0
  var day = 0

  while (i < n) {
    day += 1
    val pending = mutable.Set.empty[Int]
    do {
      pending += (as(i) - 1)
      pending -= i
      i += 1
    } while (pending.nonEmpty)
  }

  println(day)

  Console.flush
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N, -1)
    var ans = 0
    var p = 0
    var mys = 0
    while(p < N) {
      mys = A(p)
      while(mys > p) {
        p += 1
        mys = max(mys, A(p))
      }
      debug(s"p:$p mys:$mys")
      ans += 1
      p += 1
    }
    out.println(ans)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

object Foo extends App {
  val Array(n) = readints
  val a = readints

  var r, days = 0
  for (i <- 0 until n) {
    if (a(i) > r)
      r = a(i)
    if (r == i + 1)
      days += 1
  }

  println(days)

  import scala.io.StdIn.readLine
  def readints() = readLine.split(" ").map(_.toInt)
}


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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, K = sc.nextInt()
    val s = sc.next()
    var t = ""

    def find: Option[Int] = {
      rep_r(min(t.length, s.length)) { j =>
        if (s.substring(0, j) == t.substring(t.length - j)) return Some(j)
      }
      None
    }

    rep(K) { _ =>
      find match {
        case Some(j) => t += s.substring(j)
        case None => t += s
      }
    }

    out.println(t)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  var sameCount = (0 to n/2).filter(x => t.take(x) == t.takeRight(x)).last
  var s = t.dropRight(sameCount) * k + t.takeRight(sameCount)
  val lastStart = s.sliding(n).zipWithIndex.filter(_._1 == t).toList(k-1)._2
  s = s.take(lastStart + n)
  println(s)
}

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

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextInt
    val s = in.next

    var maxLen = 0

    for (i <- 1 until n) {
      if (s.take(i) == s.takeRight(i)) {
        maxLen = i
      }
    }

    val suffix = s.drop(maxLen)
    print(s)
    for (_ <- 1 until k) {
      print(suffix)
    }
    println()
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }
}

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

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextInt
    val s = in.next
    val t = (0 until n).find { i =>
      s.substring(0, n - i - 1) == s.substring(i + 1)
    }.get
    print(s)
    (1 until k).foreach { _ =>
      print(s.substring(n - t - 1))
    }
    println
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  val sameCount = t.take(n/2).zipWithIndex.takeWhile(x => t.charAt(n-1-x._2) == x._1).length
  println(t.dropRight(sameCount) * k + t.takeRight(sameCount))
}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  var sameCount = (0 to n/2).filter(x => t.take(x) == t.takeRight(x)).last

  if (sameCount == n/2 && t.forall(_ == t.head)) {
    // All chars the same
    sameCount = n - 1
  }
  println(t.dropRight(sameCount) * k + t.takeRight(sameCount))
}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  var sameCount = t.take(n/2).zipWithIndex.takeWhile(x => t.charAt(n-1-x._2) == x._1).length
  if (sameCount == n/2 && n > 1 && t.charAt(n/2) == t.charAt(n/2-1)) {
    // All chars the same
    sameCount = n - 1
  }
  println(t.dropRight(sameCount) * k + t.takeRight(sameCount))
}


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

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

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

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

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

    val t = readInt()

    for (tt <- 1 to t) {
        var s = readString()
        var cnt = 0
        for (c <- s) {
            if (c == 'N')
                cnt += 1
        }
        if (cnt == 1) {
            writer.println("NO")
        } else {
            writer.println("YES")
        }

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

import scala.io.StdIn._

object Main extends App {
    val nums = readInt()
    for (i <- 0 until nums) {
        val row  = readLine()
        if (row.count(_=='N') == 1) {
            println("NO")
        }
        else {
            println("YES")
        }
    }
}


object A {
    def main(args: Array[String]) {
        var n = scala.io.StdIn.readInt();
        var bs = Array.ofDim[Int](4, n, n);
        //println(bs(0)(1).getClass.toString())
        for(b <- 0 until 4){
            for(i <- 0 until n){
                bs(b)(i) = scala.io.StdIn.readLine().split("").map( _.toInt );
            }
            scala.io.StdIn.readLine();
        }

        val ps = List(0, 1, 2, 3).permutations
        var ans = n * n * 4;
        for(p <- ps){
            val t = cost(bs, p);
            ans = math.min(ans, t);
        }

        println(ans);
    }

    def cost(bs: Array[Array[Array[Int]]], p: List[Int]): Int = {
        //println(bs.size)
        //println(p)
        var same = 0;
        var diff = 0;
        val n = bs(0).size;
        for(b <- 0 until 4){
            for(i <- 0 until n){
                for(j <- 0 until n){
                    if(bs(p(b))(i)(j) == (i + j + (b % 2)) % 2) same += 1;
                    else diff += 1;
                }
            }
        }
        return math.min(same, diff);
    }
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n = r.read[Int]
    val b1, b2, b3, b4 = r.read[List[String]](n).mkString
    val n2 = n * n
    val sb = ("10" * n2).take(n2)
    val sw = ("01" * n2).take(n2)

    def m(s1: String, s2: String) =
      s1.zip(s2).foldLeft(0) {
        case (acc, (c, d)) => if (c == d) acc else acc + 1
      }

    val mb1 = m(b1, sb)
    val mb2 = m(b2, sb)
    val mb3 = m(b3, sb)
    val mb4 = m(b4, sb)

    val mw1 = m(b1, sw)
    val mw2 = m(b2, sw)
    val mw3 = m(b3, sw)
    val mw4 = m(b4, sw)

    println(List(mb1 + mb2 + mw3 + mw4,
                 mb1 + mw2 + mb3 + mw4,
                 mb1 + mw2 + mw3 + mb4,
                 mw1 + mb2 + mb3 + mw4,
                 mw1 + mb2 + mw3 + mb4,
                 mw1 + mw2 + mb3 + mb4).min)
  }
}

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

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

  def this() = this(new InputStreamReader(System.in))

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

  val tokenizer = new Tokenizer(br)
}

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

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

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

    import scala.collection.generic.CanBuildFrom

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

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

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

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

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

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


object A560 {
  @inline def read = scala.io.StdIn.readLine

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

  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 = readInts(n).toSet
    if(input.contains(1)) {
      println("-1")
    } else {
      println("1")
    }
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/560/A"/>
 *
 * @author pvasilyev
 * @since 10 Apr 2016
 */
object Problem148 extends App {

  private val n: Int = scala.io.StdIn.readInt()
  private var b: Boolean  = false
  private val line: String = scala.io.StdIn.readLine()
  private val a: Array[Int] = line.split(" ").map(_.toInt)
  for (i <- 0 until n) {
    val ai: Int = a(i)
    if (ai == 1) {
      b = true
    }
  }

  if (b) {
    println(-1)
  } else {
    println(1)
  }

}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    readInt()
    val b = readLine().split(" ")
    if (b.contains("1")) println(-1)
    else print(1)
  }
}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _560A extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val notes = List.fill(n)(nextInt)
  if (notes contains 1) -1 else 1
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def counter[A] = collection.mutable.Map.empty[A, Int] withDefaultValue 0
}

object A560 {
  @inline def read = scala.io.StdIn.readLine

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

  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 = readInts(n).toSet
    if(input.contains(1)) {
      if(input.contains(2)) {
        println("-1")
      } else {
        println("2")
      }
    } else {
      println("1")
    }
  }
}


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

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

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

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

  def solve(): Unit = {
    val R, C = ni()
    val g = nm_c(R, C)
    val rowL, rowR = Array.ofDim[Int](R, C + 2) // 1-indexed
    val colT, colB = Array.ofDim[Int](C, R + 2)
    REP(R) { r =>
      REP(C) { c =>
        if (g(r)(c) == '*') rowL(r)(c + 1) = rowL(r)(c) + 1
      }
      REP_r(C) { c =>
        if (g(r)(c) == '*') rowR(r)(c + 1) = rowR(r)(c + 2) + 1
      }
    }

    REP(C) { c =>
      REP(R) { r =>
        if (g(r)(c) == '*') colT(c)(r + 1) = colT(c)(r) + 1
      }
      REP_r(R) { r =>
        if (g(r)(c) == '*') colB(c)(r + 1) = colB(c)(r + 2) + 1
      }
    }

    var cntStars = 0
    val stars = Array.ofDim[Int](R, C) // 中心も含めた長さ
    REP(R) { r =>
      REP(C) { c =>
        if (g(r)(c) == '*') {
          val len = min(min(rowL(r)(c + 1), rowR(r)(c + 1)), min(colT(c)(r + 1), colB(c)(r + 1)))
          if (len > 1) {
            stars(r)(c) = len
            cntStars += 1
          }
        }
      }
    }

    val paint = Array.fill[Char](R, C)('.')

    type StepFn = (Int, Int) => Unit
    def paintIt(acc: StepFn => Unit) = {
      var cnt = 0
      def step(r: Int, c: Int) = {
        cnt = max(stars(r)(c), cnt - 1)
        if (cnt > 0) paint(r)(c) = '*'
      }

      acc(step)
    }

    REP(R) { r =>
      paintIt(step => REP(C)(c => step(r, c)))
      paintIt(step => REP_r(C)(c => step(r, c)))
    }
    REP(C) { c =>
      paintIt(step => REP(R)(r => step(r, c)))
      paintIt(step => REP_r(R)(r => step(r, c)))
    }

    var ok = true
    REP(R) { r =>
      REP(C) { c =>
        ok &&= g(r)(c) == paint(r)(c)
      }
    }

    if (!ok) out.println(-1)
    else {
      out.println(cntStars)
      REP(R) { r =>
        REP(C) { c =>
          if (stars(r)(c) > 0) out.println(s"${r+1} ${c+1} ${stars(r)(c)-1}")
        }
      }
    }
  }

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

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

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

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

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

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

import scala.collection.mutable.ListBuffer

object CF501E extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val n = in.nextInt
    val m = in.nextInt
    val grid = new Array[Array[Boolean]](n).map(_ => in.next.toCharArray.map(_ == '*'))

    var stars = new ListBuffer[(Int,Int,Int)]()

    for (x <- 1 until n-1;
         y <- 1 until m-1) {
      if (grid(x)(y)) {
        val maxSize = findMaxSize(x, y, 0)
        if (maxSize > 0)
          stars += ((x, y, maxSize))
      }
    }

    def findMaxSize(x: Int, y: Int, currentMax: Int): Int = {
      try {
        if (grid(x)(y-currentMax-1) && grid(x)(y+currentMax+1) && grid(x-currentMax-1)(y) && grid(x+currentMax+1)(y)) {
          return findMaxSize(x, y, currentMax + 1)
        } else {
          return currentMax
        }
      } catch {
        case _: ArrayIndexOutOfBoundsException => return currentMax
      }
    }

    val newGrid = Array.ofDim[Boolean](n, m)
    for (star <- stars) {
      val (x, y, size) = star
      newGrid(x)(y) = true
      for (i <- 1 to size) {
        newGrid(x+i)(y) = true
        newGrid(x-i)(y) = true
        newGrid(x)(y+i) = true
        newGrid(x)(y-i) = true
      }
    }

    if (grid.deep == newGrid.deep) {
      out.println(stars.length)
      out.println(stars.map(s => (s._1+1) + " " + (s._2+1) + " " + s._3).mkString("\n"))
    } else {
      out.println("-1")
    }
  }

  solve
  out.flush
  out.close
}