object qa {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt()
    for (_ <- 0 until n) {
      val i = scala.io.StdIn.readInt()
      val str = {
        if (i >= 1900) "Division 1"
        else if (i >= 1600) "Division 2"
        else if (i >= 1400) "Division 3"
        else "Division 4"
      }
      println(str)
    }
  }
}

import scala.io.StdIn

/**
 * На Codeforces пользователи разделены на 4 дивизиона по их рейтингу:
 *
 * Для 1-го дивизиона: 1900≤rating
 * Для 2-го ивизиона: 1600≤rating≤1899
 * Для 3-го дивизиона: 1400≤rating≤1599
 * Для 4-го дивизиона: rating≤1399
 * Учитывая rating, выведите, к какому дивизиону относится rating.
 *
 * Входные данные
 * Первая строка ввода содержит целое число 𝑡 (1≤𝑡≤104) — количество наборов входных данных в тесте.
 *
 * Описание каждого набора состоит из одной строки, содержащей одно целое число rating (−5000≤rating≤5000).
 *
 * Выходные данные
 * Для каждого набора входных данных выведите единственную строку, содержащую дивизион в формате «Division X», где 𝑋 — целое число от 1 до 4, представляющее дивизион для соответствующего рейтинга.
 */

object Task1 extends App {
  def getNextNum: Int = StdIn.readLine().toInt

  val inputSize = getNextNum

  for (_ <- 0 until inputSize) {
    val rating = getNextNum

    if (rating <= 1399) {
      println("Division 4")
    } else {
      if (rating <= 1599) {
        println("Division 3")
      } else {
        if (rating <= 1899) {
          println("Division 2")
        } else {
          println("Division 1")
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // ======================================

  def solve(n: Int) = {
    "Division " + (n match {
      case i if (i >= 1900) => 1
      case i if (i >= 1600) => 2
      case i if (i >= 1400) => 3
      case i => 4
    })
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt

    for (
      i <- 0 until cases;
      n = readLine().toInt
    ) println(solve(n))
  }
}


//package codeforces.contest1197

/*
len means the mutiple of m u r checking backwards from your current position as u need to check only multiples of m for the correct answer from any given position

 */
object YetAnotherSubarrayProblem {

  type Index = Int

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = io.StdIn.readLine().split(" ").map(_.toInt)
    val elements = io.StdIn.readLine().split(" ").map(_.toInt)

    val prefixSum = elements.scanLeft(0l)(_ + _).tail

    def sum(l: Int, r: Int): Long = prefixSum(r) - (if (l > 0) prefixSum(l - 1) else 0)

    val best = new Array[Long](n)

    val result = (0 until n).foldLeft(0l) { case (res, i) =>
      best(i) = (sum(i - m + 1, i) - k + (if (i - m >= 0) best(i - m) else 0)) max 0
      val maxAhead = (1 to m).filter(_ + i < n).foldLeft(res) { (newRes, j) =>
        newRes max (best(i) + sum(i + 1, i + j) - k)
      }
      res max best(i) max maxAhead
    }

    println(result)

  }

}

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  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 = 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) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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 scala.reflect.ClassTag

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, M, K = ni()
    val A = na(N)
    val C = cumSum(A)

    debug(C)
    val zero = -1e18.toLong

    var ans = 0L
    val tree = new BIT(N, zero)(max)
    REP(M) { ms =>
      REP(M) { mt =>
        debug(s"ms:$ms mt:$mt")
        tree.clear()

        var i = 0
        while(i * M + mt < N) {
          val t = i * M + mt
          val v = C(t + 1) - (i+1).toLong * K
          tree.add(N - 1 - t, v)
          debug(s"updateTree(${N - 1 - t}, $v)")
          i += 1
        }
        i = 0
        var t = mt
        var s = ms
        while(s < N) {
          while(t < s && t + M < N) {
            t += M
          }
          debug(s"s:$s t:$t")
          if (s <= t) {
            DEBUG(
              REP(N) { i =>
                debug(s"tree.sum(${i+1}):${tree.sum(i + 1)}")
              }
            )
            debug(s"tree:${tree.bit.mkString(" ")}")
            val lst = tree.sum(N - t)
            if (lst != zero) {
              val add = if (ms > mt) K else 0
              val v = lst - C(s) + i.toLong * K + add
              debug(s"lst:$lst add:$add v:$v")
              ans = max(ans, v)
            }
          }
          s += M
          i += 1
        }
      }
    }

    out.println(ans)
  }

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

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

    def clear(): Unit = {
      java.util.Arrays.fill(bit, zero)
    }

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

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

    def sumAll: Long = sum(n)

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

    def lowerBound(W: Long)(sub: (Long, Long) => Long, lt: (Long, Long) => Boolean): 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
      }
      x
    }
  }

  class SegmentTree(n: Int, zero: Long)(f: (Long, Long) => Long) {
   private val N = {
     val a = Integer.highestOneBit(n)
     if (a == n) a else a << 1
   }
   private val dat: Array[Long] = if (zero != 0){
     Array.fill(2 * N)(zero)
   } else {
     Array.ofDim(2 * N)
   }

   def update(i: Int, a: Long): Unit = {
     assert(i < n)
     var ix = i + N
     dat(ix) = a
     while(ix > 1) {
       dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
       ix >>= 1
     }
   }

   /**
     * [a, b)
     */
   def query(a: Int, b: Int): Long = {
     assert(a < n && b <= n)

     var res: Long = zero
     var left = a + N
     var right = b - 1 + N

     while(left <= right) {
       if ((left & 1) == 1) res = f(res, dat(left))
       if ((right & 1) == 0) res = f(res, dat(right))
       left = (left + 1) >> 1 // 右の子供なら右の親に移動
       right = (right - 1) >> 1 // 左の子供なら左の親に移動
     }

     res
   }

    def clear(): Unit = {
      java.util.Arrays.fill(dat, zero)
    }
 }
}

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  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 = 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) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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 scala.reflect.ClassTag

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, M, K = ni()
    val A = na(N)
    val C = cumSum(A)

    debug(C)
    val zero = -1e18.toLong - 10

    var ans = 0L
    val tree = new SegmentTree(N, zero)(max)
    REP(M) { ms =>
      REP(M) { mt =>
        debug(s"ms:$ms mt:$mt")
        tree.clear()

        var i = 0
        while(i * M + mt < N) {
          val t = i * M + mt
          val v = C(t + 1) - (i+1).toLong * K
          tree.update(t, v)
          debug(s"updateTree($t, $v)")
          i += 1
        }
        i = 0
        var t = mt
        var s = ms
        while(s < N) {
          while(t < s && t < N) {
            tree.update(t, zero)
            t += M
          }
          debug(s"s:$s t:$t")
          val lst = tree.query(0, N)
          if (lst != zero) {
            val add = if (ms > mt) K else 0
            val v = lst - C(s) + i.toLong * K + add
            debug(s"lst:$lst add:$add v:$v")
            ans = max(ans, v)
          }
          s += M
          i += 1
        }
      }
    }

    out.println(ans)
  }

  class SegmentTree(n: Int, zero: Long)(f: (Long, Long) => Long) {
   private val N = {
     val a = Integer.highestOneBit(n)
     if (a == n) a else a << 1
   }
   private val dat: Array[Long] = if (zero != 0){
     Array.fill(2 * N)(zero)
   } else {
     Array.ofDim(2 * N)
   }

   def update(i: Int, a: Long): Unit = {
     assert(i < n)
     var ix = i + N
     dat(ix) = a
     while(ix > 1) {
       dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
       ix >>= 1
     }
   }

   /**
     * [a, b)
     */
   def query(a: Int, b: Int): Long = {
     assert(a < n && b <= n)

     var res: Long = zero
     var left = a + N
     var right = b - 1 + N

     while(left <= right) {
       if ((left & 1) == 1) res = f(res, dat(left))
       if ((right & 1) == 0) res = f(res, dat(right))
       left = (left + 1) >> 1 // 右の子供なら右の親に移動
       right = (right - 1) >> 1 // 左の子供なら左の親に移動
     }

     res
   }

    def clear(): Unit = {
      java.util.Arrays.fill(dat, zero)
    }
 }
}

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  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 = 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) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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 scala.reflect.ClassTag

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, M, K = ni()
    val A = na(N)
    val C = cumSum(A)

    debug(C)
    val zero = -1e9.toLong - 10

    var ans = 0L
    REP(M) { ms =>
      REP(M) { mt =>
        debug(s"ms:$ms mt:$mt")
        val tree = new SegmentTree(N, zero)(max)

        var i = 0
        while(i * M + mt < N) {
          val t = i * M + mt
          val v = C(t + 1) - (i+1).toLong * K
          tree.update(t, v)
          debug(s"updateTree($t, $v)")
          i += 1
        }
        i = 0
        var t = mt
        var s = ms
        while(s < N) {
          while(t < s && t < N) {
            tree.update(t, zero)
            t += M
          }
          debug(s"s:$s t:$t")
          val lst = tree.query(0, N)
          if (lst != zero) {
            val add = if (ms > mt) K else 0
            val v = lst - C(s) + i.toLong * K + add
            debug(s"v:$v")
            ans = max(ans, v)
          }
          s += M
          i += 1
        }
      }
    }

    out.println(ans)
  }

  class SegmentTree(n: Int, zero: Long)(f: (Long, Long) => Long) {
   private val N = {
     val a = Integer.highestOneBit(n)
     if (a == n) a else a << 1
   }
   private val dat: Array[Long] = if (zero != 0){
     Array.fill(2 * N)(zero)
   } else {
     Array.ofDim(2 * N)
   }

   def update(i: Int, a: Long): Unit = {
     assert(i < n)
     var ix = i + N
     dat(ix) = a
     while(ix > 1) {
       dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
       ix >>= 1
     }
   }

   /**
     * [a, b)
     */
   def query(a: Int, b: Int): Long = {
     assert(a < n && b <= n)

     var res: Long = zero
     var left = a + N
     var right = b - 1 + N

     while(left <= right) {
       if ((left & 1) == 1) res = f(res, dat(left))
       if ((right & 1) == 0) res = f(res, dat(right))
       left = (left + 1) >> 1 // 右の子供なら右の親に移動
       right = (right - 1) >> 1 // 左の子供なら左の親に移動
     }

     res
   }
 }
}


import scala.io.StdIn._

object B extends App {
  val n = readInt()
  val first = readLine().split(" ").map(_.toInt)
  val second = readLine().split(" ").map(_.toInt)
  val cross = readLine().split(" ").map(_.toInt)

  var offset = 0
  val answer = Array.ofDim[Int](n)
  for (curr <- n - 1 to 0 by -1) {
    var ifGoUp = offset + cross(curr) + first.take(curr).sum
    answer(curr) = ifGoUp
    if (curr > 0) offset += second(curr - 1)
  }

  println(answer.sorted.take(2).sum)

}

/*
4
1 2 3
3 2 1
3 2 2 3
 */

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a1 = in.next().split(" ").map(_.toInt)
  val a2 = in.next().split(" ").map(_.toInt).reverse
  val b = in.next().split(" ").map(_.toInt)
  val a1sum = a1.scan(0){_ + _}
  val a2sum = a2.scan(0){_ + _}.reverse
  val path = a1sum.zip(a2sum)
  val res = path.indices.map(i => a1sum(i) + a2sum(i) + b(i)).sorted.take(2).sum

  println(res)
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _586B extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val r1 = IndexedSeq.fill(n-1)(nextInt)
  val r2 = IndexedSeq.fill(n-1)(nextInt)
  val c = IndexedSeq.fill(n)(nextInt)

  val choices = c.zipWithIndex map {case (x, i) =>
    val (s1, s2) = (r1.take(i), r2.takeRight(n - i - 1))
    x + s1.sum + s2.sum
  }

  choices.sorted.take(2).sum
}) {
  override def format(result: Result) = super.format(result)
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import java.io._

object B_LaurentyAndShop {

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

    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val number = br.readLine().trim().toInt
    val row1Str = br.readLine().trim().split(" ")
    val row2Str = br.readLine().trim().split(" ")
    val aveStr = br.readLine().trim().split(" ")

//    val number = 4
//    val row1Str = "1 2 3".split(" ")
//    val row2Str = "3 2 1".split(" ")
//    val aveStr = "3 2 2 3".split(" ")

//    val number = 3
//    val row1Str = "1 2".split(" ")
//    val row2Str = "3 3".split(" ")
//    val aveStr = "2 1 3".split(" ")

//    val number = 2
//    val row1Str = "1".split(" ")
//    val row2Str = "1".split(" ")
//    val aveStr = "1 1".split(" ")

    val row1 = row1Str.map { x=>Integer.parseInt(x)}
    val row2 = row2Str.map { _.toInt}
    val ave = aveStr.map { _.toInt}

    var row1Sum = 0;
    var row2Sum = 0;
    row2.foreach { x => row2Sum += x }
    //foldLeft(0)((x:Int,y:Int)=> x+y)

    val solutions = Array.fill(number){0}
    for (i <- 0 until number) {
      solutions(i) = row1Sum + ave(i) + row2Sum
      if (i + 1 <= row1.length) {
        row1Sum += row1(i)
        row2Sum -= row2(i)
      }
    }

    scala.util.Sorting.quickSort(solutions)
    var sum = 0;
    if (solutions.length > 0) {
      sum += solutions(0)
    }
    if (solutions.length > 1) {
      sum += solutions(1)
    }
    println(sum)

  }
}


object B extends App {
  case class Savings(x: Int, as: List[Int])

  val t = scala.io.StdIn.readInt()

  private def wealthy(s: Savings): Int = {
    val Savings(x, as) = s

    val (ps, rs) = as.sorted.span(_ < x)
    val rl = rs.length

    val overage: Long = rs.foldLeft(0L)(_ + _ - x)

    val pl = ps.reverse
      .foldLeft((overage, 0)) {
        case ((overage, count), a) =>
          if (overage < x - a) (overage, count)
          else (overage - x + a, count + 1)
      }
      ._2

    rl + pl
  }

  val input = (0 until t)
    .foldLeft(List.empty[Savings]) { (acc, _) =>
      val Array(n, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Savings(x, as) :: acc
    }
    .reverse

  val output = input.map(wealthy)

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val totalCases = in.nextInt()
    (1 to totalCases).foreach{ _ =>
      val n = in.nextInt()
      val x = in.nextLong()
      val a = (1 to n).map(_ => in.nextLong()).sorted.reverse.toArray
      var ans = 0
      var cumSum = 0L
      a.indices.foreach{ i =>
        val newSum = cumSum + a(i)
        if(newSum >= x*(i+1)){
          ans = i+1
        }
        cumSum = newSum
      }
      out.println(ans)

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object B extends App {
  case class Savings(x: Int, as: List[Int])

  val t = scala.io.StdIn.readInt()

  private def wealthy(s: Savings): Int = {
    val Savings(x, as) = s

    val (ps, rs) = as.sorted.span(_ <= x)
    val rl = rs.length

    val overage = rs.foldLeft(0L)(_ + _ - x)

    val pl = ps
      .foldLeft(List.empty[Int]) {
        case (acc, a) =>
          val deficit = acc.foldLeft((x - a).toLong)(_ + x - _)

          if (overage - deficit >= 0) a :: acc
          else acc

      }
      .length

    rl + pl
  }

  val input = (0 until t)
    .foldLeft(List.empty[Savings]) { (acc, _) =>
      val Array(n, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Savings(x, as) :: acc
    }
    .reverse

  val output = input.map(wealthy)

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


import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      val ch = s(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch >= '0' && ch <= '9') breeders(i)(j) = ch - '0'
        else if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      val ch = s(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch >= '0' && ch <= '9') breeders(i)(j) = ch - '0'
        else if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)
  val djs = Array(0, 0, -1, 1)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (isFree.isDefinedAt(ni)) {
        val nj = j + djs(m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill[Byte](r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      val ch = s(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch >= '0' && ch <= '9') breeders(i)(j) = (ch - '0').toByte
        else if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val s = Array.ofDim[String](r)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    s(i) = readString
    for (j <- 0 until c) {
      val ch = s(i)(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)
  dists(exit._1)(exit._2) = 0

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit; if (s(i)(j) > '0' && s(i)(j) <= '9')) sum += (s(i)(j) - '0')

  println(sum)
}

import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val s = Array.ofDim[String](r)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    s(i) = readString
    for (j <- 0 until c) {
      val ch = s(i)(j)
      if (ch != 'T') {
        isFree(i) += j
        if (ch == 'S') start = (i, j)
        else if (ch == 'E') exit = (i, j)
      }
    }
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)
  dists(exit._1)(exit._2) = 0

  val dis = Array(-1, 1, 0, 0)

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + dis(3 - m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit; ch = s(i)(j); if (ch > '0' && ch <= '9')) sum += (ch - '0')

  println(sum)
}

import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    for (j <- 0 until c) {
      if (s(j) != 'T') isFree(i) += j
      if (s(j) >= '0' && s(j) <= '9') breeders(i)(j) = s(j) - '0'
      else if (s(j) == 'S') start = (i, j)
      else if (s(j) == 'E') exit = (i, j)
    }
  }
  if (r == 1000) println("read")
  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(Int.MaxValue)

  val dis = Array(-1, 1, 0, 0)
  val djs = Array(0, 0, -1, 1)
  if (r == 1000) println("init")

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    val nextDist = dists(i)(j) + 1
    var m = 0
    while (m < 4) {
      val ni = i + dis(m)
      if (ni >= 0 && ni < r) {
        val nj = j + djs(m)
        if (isFree(ni)(nj)) {
          toVisit += ((ni, nj))
          isFree(ni)(nj) = false
          dists(ni)(nj) = nextDist
        }
      }
      m += 1
    }
  }
  if (r == 1000) println("shortest")

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}

import scala.collection._

object B extends App {

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

  val Array(r, c) = readInts(2)

  val isFree = Array.fill(r)(new mutable.BitSet(c))
  val breeders = Array.fill(r, c)(0)

  var start = (0, 0)
  var exit = (0, 0)

  for (i <- 0 until r) {
    val s = readString
    isFree(i) ++= s.indices.filter(s(_) != 'T')
    s.indices.withFilter(j => s(j) >= '0' && s(j) <= '9').foreach(j => breeders(i)(j) = s(j) - '0')
    var sj = s.indexOf('S')
    if (sj >= 0) start = (i, sj)
    val ej = s.indexOf('E')
    if (ej >= 0) exit = (i, ej)
  }

  val toVisit = mutable.Queue(exit)
  isFree(exit._1)(exit._2) = false
  val dists = Array.fill(r, c)(0)

  val moves = Array((-1, 0), (1, 0), (0, -1), (0, 1))

  while (!toVisit.isEmpty) { // BFS
    val (i, j) = toVisit.dequeue
    for ((di, dj) <- moves; ni = i + di; nj = j + dj; if isFree.isDefinedAt(ni) && isFree(ni)(nj)) {
      toVisit += ((ni, nj))
      isFree(ni)(nj) = false
      dists(ni)(nj) = dists(i)(j) + 1
    }
  }

  val limit = dists(start._1)(start._2)
  var sum = 0

  for (i <- 0 until r; j <- 0 until c; if dists(i)(j) <= limit) sum += breeders(i)(j)

  println(sum)
}


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

object test6 extends App {
    val n=readInt
    val mat=Array.ofDim[Int](n+1,n+1)
    val rows=new Array[Int](n+1)
    val cols=new Array[Int](n+1)

    for(_<-1 until n){
        val Array(x,y)=readLine.split(" ").map(_.toInt)
        mat(x)(y)=1
        rows(x)+=1
        cols(y)+=1
    }

    val swapRows=(i:Int, j:Int)=>{
        val tmp=mat(i)
        mat(i)=mat(j)
        mat(j)=tmp

        val tt=rows(i)
        rows(i)=rows(j)
        rows(j)=tt
    }

    val swapCols=(i:Int, j:Int)=>{
        for(k<-1 to n){
            val tmp=mat(k)(i)
            mat(k)(i)=mat(k)(j)
            mat(k)(j)=tmp
        }
        val tmp=cols(i)
        cols(i)=cols(j)
        cols(j)=tmp
    }

    var ab=collection.mutable.ArrayBuffer[String]()
    for(i<-n to 1 by -1){
        var col=i
        while(col>0 && cols(col)>0) col-=1
        if(col>0 && col!=i){
            swapCols(i,col)
            ab+="2 %d %d".format(col, i)
        }

        var row=i
        while(row>0 && rows(row)==0) row-=1
        if(row>0 && row!=i){
            swapRows(i,row)
            ab+="1 %d %d".format(row,i)
        }

        for(j<-1 to i) if(mat(i)(j)==1) cols(j)-=1
    }
    println(ab.size)
    ab.foreach(println)
}

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

object test6 extends App {
    val n=readInt
    val mat=Array.ofDim[Int](n+1,n+1)
    val rows=new Array[Int](n+1)
    val cols=new Array[Int](n+1)

    for(_<-1 until n){
        val Array(x,y)=readLine.split(" ").map(_.toInt)
        mat(x)(y)=1
        rows(x)+=1
        cols(y)+=1
    }

    val swapRows=(i:Int, j:Int)=>{
        val tmp=mat(i)
        mat(i)=mat(j)
        mat(j)=tmp

        val tt=rows(i)
        rows(i)=rows(j)
        rows(j)=tt
    }

    val swapCols=(i:Int, j:Int)=>{
        for(k<-1 to n){
            val tmp=mat(k)(i)
            mat(k)(i)=mat(k)(j)
            mat(k)(j)=tmp
        }
        val tmp=cols(i)
        cols(i)=cols(j)
        cols(j)=tmp
    }

    var ab=collection.mutable.ArrayBuffer[String]()
    for(i<-n to 1 by -1){
        var col=i
        while(col>0 && cols(col)>0) col-=1
        if(col>0 && col!=i){
            swapCols(i,col)
            ab+="2 %d %d".format(col, i)
        }

        var row=i
        while(row>0 && rows(row)==0) row-=1
        if(row>0 && row!=i){
            swapRows(i,row)
            ab+="1 %d %d".format(row,i)
        }

        for(j<-1 to i) if(mat(i)(j)==1) cols(j)-=1
    }
    println(ab.size)
    println(ab.mkString("\n"))
}


object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val map = scala.collection.mutable.Map[String, Int]()
    for (_ <- 1 to n) {
      val name = readLine()
      map.get(name) match {
        case None =>
          map(name) = 1
          println("OK")
        case Some(i) =>
          map(name) = i + 1
          println(name + i)
      }
    }
  }
}

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

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

  val N = sc.nextInt
  sc.nextLine
  type DB = mutable.Map[String, Int]
  val db: DB = mutable.Map.empty[String, Int]
  for (_ <- 0 until N) {
    val request = sc.nextLine
    if (db.contains(request)) {
      val i = db(request) + 1
      db += (request -> i)
      out.println(request + i.toString)
    }
    else {
      db += (request -> 0)
      out.println("OK")
    }
  }
  out.close
}

import java.io.PrintWriter
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.BufferedReader
import java.util

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object C4 extends App {

  val reader = new BufferedReader(new InputStreamReader(System.in))
  var writer = new BufferedWriter(new PrintWriter(System.out))
  val n: Int = reader.readLine().toInt
  val db: mutable.HashMap[String, Int] = mutable.HashMap.empty[String, Int]
  val answer: util.ArrayList[String] = new util.ArrayList[String](n)
  for (i <- 0 until n) {
    val input = reader.readLine()
    if (!db.contains(input)) {
      writer.write("OK\n")
      db += (input -> 1)
    } else {
      var i1: Int = db.get(input).get
      var found = false
      while (!found) {
        if (!db.contains(input + i1)) {
          found = true
        } else {
          i1 += 1
        }
      }
      val s: String = input + i1 + "\n"
      writer.write(s)
      db += (input -> (i1 + 1))
      db += (input + i1 -> 1)
    }
  }

  writer.close()
  reader.close()
}

object Cf4C extends App {
  val d =collection.mutable.Map[String, Int]()
  for(_ <-1 to readInt()){
    val s = readLine
    d get s match {
      case Some(x) => {println(s+x);d(s)=x+1}
      case None => {println("OK");d(s)=1}
    }
  }
}

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

object C {

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

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

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

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

  def solve = {
    val n = nextInt
    val names = new util.HashSet[String]()
    val namedInd = new util.HashMap[String, Int]()
    for (i <- 0 until n) {
      val name = next
      if (names.contains(name)) {
        val ind = namedInd.get(name)
        out.println(name + ind.toString)
        names.add(name + ind.toString)
        namedInd.remove(name)
        namedInd.put(name, ind + 1)
      } else {
        names.add(name)
        namedInd.put(name, 1)
        out.println("OK")
      }
    }
  }

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

object P4C {
    def main(args : Array[String]) {
        val n = readLine.toInt
        val d = collection.mutable.Map[String, Int]()
        for (_ <- 1 to n) {
            val s = readLine
            d get s match {
                case Some(x) => {println(s + x); d(s) = x + 1}
                case None => {println("OK"); d(s) = 1}
            }
        }
    }
}

import scala.collection.mutable.Map
object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val map = Map[String, Int]()
    for (i <- 1 to n) {
      val str = readLine()
      if (map.contains(str)) {
        map(str) += 1
        println(str + map(str).toString)
      }
      else {
        map += (str -> 0)
        println("OK")
      }
    }
  }
}

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

object _4_C extends App {
  val n = readInt()
  val counter = new mutable.HashMap[String, Int]

  for (_ <- 1 to n) {
    val name = readLine()
    var c = counter.getOrElseUpdate(name, 0)
    if (c == 0) {
      println("OK")
    }
    else {
      println(s"$name$c")
    }
    c += 1
    counter(name) = c
  }
}

import scala.collection.mutable.HashMap

object RegistrationSystem{
    class Name(var nameString : String = "",var count : Int = 0,var printedCount : Int = 0)
    def main(args : Array[String]){

        var n : Int = readLine.toInt
        var namesMap : HashMap[String,Name] =  new HashMap[String,Name]()
        var namesArray : Array[String] = new Array[String](n)
        for(i <- 0 to n-1){
            var name : String = readLine
            namesArray(i) = name
            if (namesMap.contains(name)){
                namesMap(name).count += 1
            }
            else{
                namesMap.put(name,new Name(name,1,0))
            }
        }
        for(name <- namesArray){
            if (namesMap(name).printedCount == 0){
                println("OK")
            }
            else{
                println(name + namesMap(name).printedCount)
            }
            namesMap(name).printedCount += 1
        }
    }
}

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

/**
  * Created by nhan on 5/30/16.
  */

object Registrator {

  def main(args: Array[String]) {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(System.out)
    val dict = collection.mutable.HashMap.empty[String, Int]
    val numLine = br.readLine().toInt
    (1 to numLine).foreach { _ =>
        val line = br.readLine()
        if (dict contains line) {
          val value = dict(line) + 1
          dict.update(line, value)
          out.println(line + value)
        } else {
          dict.update(line, 0)
          out.println("OK")
        }
    }
    out.close
  }
}

import scala.collection.mutable._

object Main {
    def main(args : Array[String]) {
        val n = Integer valueOf(readLine())
        val db = new HashMap[String, Int]

        for(i <- 0 until n) {
            val name = readLine()
            if(!(db contains name)) {
                db += name -> 1
            } else {
                db += name -> (db(name) + 1)
            }

            if(db(name) == 1) {
                println("OK");
            } else {
                println(name + (db(name) - 1))
            }
        }
    }
}

import scala.collection.mutable._

object Main {
    def main(args : Array[String]) {
        val n = Integer valueOf(readLine())
        val db = new HashMap[String, Int]

        for(i <- 0 until n) {
            val name = readLine()

            db get name match {
                case Some(k) => {
                    println(name + k);
                    db += name -> (k + 1)
                }

                case None => {
                    println("OK")
                    db += name -> 1
                }
            }
        }
    }
}

import java.util.Scanner

object CRegSystem extends App {

  val scanner = new Scanner(System.in)
  val num = scanner.nextInt()

  val m = scala.collection.mutable.HashMap.empty[String, Int]

  val queries = ((0 until num) map (it => scanner.next())).toList

  queries.foreach {
    item =>
      m.get(item) match {
        case Some(v) =>
          m.put(item, v + 1)
          println("" + item + v)
        case None =>
          m.put(item, 1)
          println("OK")
      }
  }

}

import scala.collection.mutable

object C4 {
  @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 map = mutable.Map.empty[String, Int].withDefaultValue(0)
    for (i <- 0 until n) {
      val name = scala.io.StdIn.readLine
      if(map.contains(name)) {
        println(s"${name}${map(name)}")
        map(name) += 1
      } else {
        map(name) = 1
        println("OK")
      }
    }
  }
}

import scala.io.StdIn

object A extends App {

  var map: Map[String, Int] = Map()

  val n = StdIn.readInt()
  (1 to n).foreach { _ =>
    val s = StdIn.readLine()
    if(map.contains(s)) {
      map = map + (s -> (map(s) + 1))
      println(s + map(s))
    } else {
      map = map + (s -> 0)
      println("OK")
    }
  }
}

object P4C {
    def main(args : Array[String]) {
        val n = readLine.toInt
        val d = collection.mutable.Map[String, Int]()
        for (_ <- 1 to n) {
            val s = readLine
            if (d contains s) {
                val ds = d(s)
                println(s + ds)
                d(s) = ds + 1
            } else {
                println("OK")
                d(s) = 1
            }
        }
    }
}

import java.util

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object C4 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val db: mutable.HashSet[String] = mutable.HashSet.empty[String]
  val answer: util.ArrayList[String] = new util.ArrayList[String](n)
  for (i <- 0 until n) {
    val input = scala.io.StdIn.readLine()
    if (!db.contains(input)) {
      answer.add("OK")
      db += input
    } else {
      var found = false
      var i: Int = 1
      while (!found) {
        if (!db.contains(input + i)) {
          found = true
        } else {
          i += 1
        }
      }
      answer .add (input + i)
      db += (input + 1)
    }
  }

  println(answer.toArray.mkString("\n"))
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Int](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) += 1
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((count, 0), diff)) => sum + count
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, n), false)) if n == 1 => sum + 1
    case(sum, ((count, _), _)) => sum
  })
}

object A extends App {

  def solve(n: Int, as: Array[Int], bs: Array[Int]): Int = {

     n - as.indices.count(i => bs.indices.exists(j => as(i) == bs(j) && i != j))
  }

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  val as = Array.ofDim[Int](n)
  val bs = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    val Array(a, b) = readInts
    as(i) = a
    bs(i) = b
  }

  println(solve(n, as, bs))
}

// package R187d2

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

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

  val N = sc.nextInt
  val xs = Array.fill(N, 2)(sc.nextInt)

  def isUnableToOpen(i: Int): Boolean = {
    @tailrec
    def loop(j :Int): Boolean =
      if (j == N) true
      else if (i == j) loop(j + 1)
      else if (xs(i)(0) == xs(j)(1)) false
      else loop(j + 1)

    loop(0)
  }

  out.println(List.range(0, N).count(isUnableToOpen))
  out.close
}

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

  val n = readInt()

  val (as, bs) = (0 until n).foldLeft((List.empty[Int], List.empty[Int])) {
    case ((as, bs), _) =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      (a :: as, b :: bs)
  }

  val ans = n - (as zip bs).collect {
    case (a, b) if a == b && bs.count(_ == a) > 1 => 1
    case (a, b) if a != b && bs.exists(_ == a)    => 1
  }.sum

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield { readLine().split(" ").map(_.toInt) }
    val Array(as, bs) = a.transpose.toArray
    val r = for {
      (x, i) <- as.zipWithIndex
      (y, j) <- bs.zipWithIndex
      if i != j
      if x == y
    } yield(i)
    println(n - r.toSet.size)
  }
}

object Second{
  def readString() : String = {
    var yo = scala.io.StdIn.readLine()
    yo
  }
  def readInt() : Int = {
    var yo = scala.io.StdIn.readInt();
    yo
  }
 def solve(n : Int , as : Array[Int] , bs : Array[Int]) : Int = {
   val ho = n - as.indices.count(i => bs.indices.exists(j => as(i) == bs(j) && i != j))
   ho
 }
   def main(args : Array[String]){
    var n = readInt()
    var as = Array.ofDim[Int](n)
    var bs = Array.ofDim[Int](n)
    for(i <- 0 until n){
      var Array(a, b ) = readString().split(" ").map(_.toInt)
      as(i) = a
      bs(i) = b
    }
    print(solve(n , as , bs))
   }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((_, false), diff)) => sum
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + 1
    case(sum, ((count, _), _)) => sum + count
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((count, false), diff)) => sum + count
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + 1
    case(sum, ((count, _), _)) => sum
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((_, false), diff)) => sum
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + count
    case(sum, ((count, _), _)) => sum + count - 1
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((count, false), diff)) => sum + count
    case(sum, ((0, _), _)) => sum
    case(sum, ((count, _), false)) => sum + count - 1
    case(sum, ((count, _), _)) => sum
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val counts = Array.ofDim[Int](1000)
  val open = Array.ofDim[Boolean](1000)
  val different = Array.ofDim[Boolean](1000)
  (1 to n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    counts(a) += 1
    open(b) = true
    different(b) = different(b) || a != b
  }
  println(counts.zip(open).zip(different).foldLeft(0) {
    case(sum, ((_, false), diff)) => sum
    case(sum, ((count, _), false)) => sum + count
    case(sum, ((count, _), _)) => sum + count - 1
  })
}

object A extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  def solve(n: Int): Int = {

  	if (n < 0) {
  	  val p = -n
  	  -math.min(p / 10, (p / 100) * 10 + p % 10)
  	} else n
  }

  val n = readString.toInt

  println(solve(n))
}

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

  val n       = readInt()
  val bottles = Array.fill(1001)(0)
  val same    = Array.fill(1001)(false)
  val opened  = Array.fill(1001)(false)

  (0 until n).foreach { _ =>
    val Array(bottle, other) = readLine().split(" ").map(_.toInt)

    bottles(bottle) += 1

    if (bottle == other) same(bottle) = true
    else opened(other) = true
  }

  same.zipWithIndex.foreach {
    case (false, _)  => ()
    case (_, bottle) => opened(bottle) = opened(bottle) || bottles(bottle) > 1
  }

  val ans = bottles.zipWithIndex.foldLeft(n) {
    case (closed, (0, _)) => closed
    case (closed, (count, bottle)) =>
      closed - (if (opened(bottle)) count else 0)
  }

  println(ans)
}

object ASerejaAndBottles extends App {
  import scala.io.StdIn._
  import scala.collection.mutable

  val n = readInt()

  val bottles      = Array.fill(1001)(0)
  val descriptions = Array.fill(1001)(List.empty[Int])

  (0 until n).foreach { _ =>
    val Array(bottle, description) = readLine().split(" ").map(_.toInt)
    bottles(bottle) += 1
    descriptions(bottle) ::= description
  }

  val ans = bottles.zipWithIndex.foldLeft(n) {
    case (closed, (_, 0)) => closed
    case (closed, (count, bottle)) =>
      descriptions(bottle).exists { opener =>
        if (opener == bottle) count > 1
        else bottles(opener) > 0
      } match {
        case true => closed - count
        case _    => closed
      }
  }

  println(ans)
}

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

  val n = readInt()

  val (as, bs) = (0 until n).foldLeft((List.empty[Int], List.empty[Int])) {
    case ((as, bs), _) =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      (a :: as, b :: bs)
  }

  val ans = n - (as zip bs).collect {
    case (a, b) if a != b && bs.exists(_ == a) => 1
  }.sum

  println(ans)
}

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

  val n = readInt()
  val ans = (0 until n).foldLeft(0) {
    case (acc, _) =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      acc + (if (a == b) 1 else 0)
  }

  println(ans)
}

object ASerejaAndBottles extends App {
  import scala.io.StdIn._
  import scala.collection.mutable

  val n = readInt()

  val bottles      = Array.fill(1001)(0)
  val opened       = Array.fill(1001)(false)

  (0 until n).foreach { _ =>
    val Array(bottle, other) = readLine().split(" ").map(_.toInt)

    bottles(bottle) += 1

    opened(other) = opened(other) ||
      (if (bottle == other) bottles(bottle) > 1 else true)
  }

  val ans = bottles.zipWithIndex.foldLeft(n) {
    case (closed, (0, _)) => closed
    case (closed, (count, bottle)) =>
      closed - (if (opened(bottle)) count else 0)
  }

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield {readLine().split(" ").map(_.toInt) }
    val f = a.filter(t => t(0) != t(1))
    if (f.size == 0) println(n)
    else {
      val Array(as, bs) = f.transpose.map(_.toSet).toArray
      val r = as -- bs
      println(n - f.size + r.size)
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield {readLine().split(" ").map(_.toInt) }
    val f = a.filter(t => t(0) != t(1))
    if (f.size == 0) println(n)
    else {
      val Array(as, bs) = f.transpose.toArray
      val bss = bs.toSet
      val r = as filter (e => ! (bss contains e))
      println(n - f.size + r.size)
    }
  }
}


/**
  * @see http://codeforces.com/contest/909/problem/C
  */

object CPythonIndentation extends App {
  val mod = 1000000007

  val n = scala.io.StdIn.readInt()

  val t = (0 until (n - 1)).foldLeft(List(1)) ((l, _) => {
    val c = scala.io.StdIn.readChar()
    if (c == 'f') 0 +: l
    else l.foldRight(List.empty[Int]) ((i, l) => {
      if (l.isEmpty) List(i)
      else ((i + l.head) % mod) +: l
    })
  }).reduce((a, b) => (a + b) % mod)

  println(t)
}

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

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

object Main extends App {

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val n = in.nextInt
  var prev = ""

  var cnt = 0
  var d = new Array[Int](n+1)

  for (i <- 0 to n-1) {

    val s = in.next
    val nd = new Array[Int](n+1)
    prev match {
      case "f" => {
        for (i <- 1 to n) nd(i) = d(i-1)
      }
      case "s" => {
        var sum = 0
        for (i <- n to 0 by -1) {
          sum += d(i)
          sum %= MOD
          nd(i) = sum
        }
      }
      case _ => nd(0) = 1
    }
    //println(nd(0))
    d = nd
    prev = s
  }

  var ans = 0
  for (k <- d) ans = (ans + k)%MOD

  out.println(ans)
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

object C extends App {

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

  val Array(n) = readInts(1)

  val MOD = 1000000007L

  val dp = Array.fill(n + 1){ 0L }
  var fCount = 0
  var prev = '-'
  dp(0) = 1
  //println(dp.mkString(" "))
  for (_ <- 0 until n) {
    val c = readLine.head
    if (prev != 'f' && c == 's') {
      for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD
    } else {
      if (prev != 'f') for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD
      if (c == 'f') {
        fCount += 1
        for (i <- fCount - 1 to 0 by -1) dp(i + 1) = dp(i)
        dp(0) = 0
      }
    }
    //println(dp.mkString(" "))
    prev = c
  }

  var sum = 0L
  for (x <- dp) sum = (sum + x) % MOD

  println(sum)
}

object C extends App {

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

  val Array(n) = readInts(1)

  val MOD = 1000000007L

  val dp = Array.fill(n + 1){ 0L }
  var fCount = 0
  var prev = '-'

  for (_ <- 0 until n) {
    val c = readLine.head
    if (prev != 'f') {
      if (c == 's') for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD
    } else if (c == 's') {
      dp(fCount) += 1
    }
    if (c == 'f') {
      fCount += 1
    }
    //println(dp.mkString(" "))
    prev = c
  }

  var sum = 0L
  for (x <- dp) sum = (sum + x) % MOD

  if (fCount == 0) sum = 1L

  println(sum)
}

/**
  * @see http://codeforces.com/contest/909/problem/C
  */

object CPythonIndentation extends App {
  val mod = 1000000007

  val N = scala.io.StdIn.readInt()

  def f(l: List[Int], m: List[Int] = List.empty): List[Int] =
    if (l.isEmpty) m
    else f(l.tail, (l.sum % mod) +: m)

  val t = (0 until N).foldLeft((List.empty[Int], 'c')) ((h, i) => {
    val c = scala.io.StdIn.readChar()
    if (i == 0) (List(1), c)
    else if (h._2 == 'f') (0 +: h._1, c)
    else (f(h._1), c)
  })._1

  println(t.sum % mod)
}


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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  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 = 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) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](26)
    REP(N) { _ =>
      val c = ns().head - 'a'
      C(c) += 1
    }

    debug(C)

    def comb(n: Int) = {
      if (n < 2) 0
      else n * (n - 1) / 2
    }

    var ans = 0
    REP(26) { i =>
      if (C(i) >= 2) {
        val f = C(i) / 2
        val s = C(i) - f
        debug(s"f:$f s:$s")
        ans += comb(f) + comb(s)
      }
    }

    out.println(ans)
  }
}

object Main extends App {

	def factorial(n: Int) : Double = {
	    var result : Double = 1

	    for ( i <- 2 to n ) {
	    	result *= i
	    }

	    return result
	}

	// your code goes here
	var n = Console.readLine
	var size : Int = n.toInt
	var arrName : Array[String] = new Array[String](size)
	var arrCount : Array[Int] = new Array[Int](30)
	var ans : Double = 0

	for ( i <- 0 to size-1) {
		arrName(i) = Console.readLine
	}

	for (i <- 0 to 29) {
		arrCount(i) = 0
	}

	for ( i <- 0 to size-1) {
		var pos : Int = arrName(i).charAt(0) - 'a'
		arrCount(pos) += 1
	}

	for (i <- 0 to 29) {
		var room1 : Int = arrCount(i)/2
		var room2 : Int = arrCount(i) - room1

		if ( room1 > 1 ) {
			ans += factorial(room1) / 2 / factorial(room1 - 2)
		}

		if ( room2 > 1 ) {
			ans += factorial(room2) / 2 / factorial(room2 - 2)
		}
	}

	println(ans.toLong)
}

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

  override def apply(io: IO): io.type = {
    val students = io.read[Seq[String]]

    val ans = students
      .groupBy(_.head)
      .mapValues(grps => pairs(grps.size))
      .values
      .sum

    io.write(ans)
  }

  def pairs(n: Int) = {
    val room1 = n/2
    val room2 = n - n/2
    ((room1*(room1 - 1))/2) + ((room2*(room2 - 1))/2)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

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

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

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

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

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

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

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

object Main extends App {

	def factorial(n: Int): Int = n match {
	    case 0 => 1
	    case _ => n * factorial(n-1)
	}

	// your code goes here
	var n = Console.readLine
	var size : Int = n.toInt
	var arrName : Array[String] = new Array[String](size)
	var arrCount : Array[Int] = new Array[Int](30)
	var ans : Long = 0

	for ( i <- 0 to size-1) {
		arrName(i) = Console.readLine
	}

	for (i <- 0 to 29) {
		arrCount(i) = 0
	}

	for ( i <- 0 to size-1) {
		var pos : Int = arrName(i).charAt(0) - 'a'
		arrCount(pos) += 1
	}

	for (i <- 0 to 29) {
		var room1 : Int = arrCount(i)/2
		var room2 : Int = arrCount(i) - room1

		if ( room1 > 1 ) {
			ans += factorial(room1) / 2 / factorial(room1 - 2)
		}

		if ( room2 > 1 ) {
			ans += factorial(room2) / 2 / factorial(room2 - 2)
		}
	}

	println(ans)
}


object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  //val out: PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt).map(x => if (x >= 0) -x - 1 else x )
  if (a.foldLeft(0)((acc, x) => if (x < 0) acc + 1 else acc) % 2 == 1) {
    var min = a.min
    for (i <- 0 until n)
      if (a(i) == min) {
        a(i) = -min - 1
        min = 0
      }
  }
  out.print(a.mkString(" "))
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    def nextDouble: Double = next.toDouble

    def nextLine: String = br.readLine
  }

}

//package round569

import scala.io.StdIn._

object TaskB extends App {
  val n = readInt
  val arr = readLine.split(" ").map(_.toInt).map(x => if(x == 0) -1 else if (x > 0) -x - 1 else x)
  if (arr.length % 2 == 0)
    println(arr.mkString(" "))
  else {
    val max = arr.min
    var flag = false
    println(arr.map {
      x =>
        if(x == max && !flag) {
          flag = true
          -x - 1
        } else {
          x
        }
    }.mkString(" "))
  }
}

import scala.io.StdIn._

object B_1180 extends App {
  val n = readInt()
  var A = readLine().split(" ").map(_.toInt)

  A = A.map { v =>
    if (v >= 0) -v - 1 else v
  }

  if (A.count(_ < 0) % 2 == 1) {
    val (_, minId) = A.zipWithIndex.minBy(_._1)
    A(minId) = -A(minId) - 1
  }

  println(A.mkString(" "))

}

import scala.io.StdIn._

object B_1180 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  var B = A.sorted

  B = B.map { v =>
    if (v >= 0) -v - 1 else v
  }

  var answer = B.product
  if (answer <= 0) {
    val (min, minId) = B.zipWithIndex.minBy(_._1)
    B(minId) = -B(minId) - 1
  }

  println(B.mkString(" "))

}

import scala.io.StdIn._

object B_1180 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  val B = A.zipWithIndex.sortBy(_._1)

  var left  = 0
  var right = n - 1

  val negatives = B.count(_._1 < 0)
  val positives = B.count(_._1 > 0)

  if (negatives % 2 == 0) {
    var right = B.length - 2
    while (right >= 0 && B(right)._1 >= 0) {
      B(right + 1) = (-B(right + 1)._1 - 1, B(right + 1)._2)
      B(right) = (-B(right)._1 - 1, B(right)._2)
      right -= 2
    }
  } else {
    var right = B.length - 1
    while (right > 0 && B(right)._1 > 0) {
      B(right) = (-B(right)._1 - 1, B(right)._2)
      right -= 1
    }
  }

  var zeros = B.count(_._1 == 0)

  val newNegatives = B.count(_._1 < 0)
  if (newNegatives % 2 == 1) {
    zeros = if (zeros % 2 == 1) zeros else zeros - 1
  } else {
    zeros = if (zeros % 2 == 0) zeros else zeros - 1
  }
  if (zeros < 0) zeros = 0

  var i = 0
  while (zeros > 0) {
    if (B(i)._1 == 0) {
      B(i) = (-1, B(i)._2)
      zeros -= 1
    }
    i += 1
  }

  println(B.sortBy(_._2).map(_._1).mkString(" "))
}

import scala.io.StdIn._

object B_1180 extends App {
  val n = readInt()
  var A = readLine().split(" ").map(_.toInt)

  A = A.map { v =>
    if (v >= 0) -v - 1 else v
  }

  var answer = A.product
  if (answer <= 0) {
    val (min, minId) = A.zipWithIndex.minBy(_._1)
    A(minId) = -A(minId) - 1
  }

  println(A.mkString(" "))

}

import scala.io.StdIn._

object B_1180 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  val B = A.sorted

  var left  = 0
  var right = n - 1

  val negatives = B.count(_ < 0)
  val positives = B.count(_ > 0)

  if (negatives % 2 == 0) {
    var right = B.length - 2
    while (right >= 0 && B(right) >= 0) {
      B(right + 1) = -B(right + 1) - 1
      B(right) = -B(right) - 1
      right -= 2
    }
  } else {
    var right = B.length - 1
    while (right > 0 && B(right) > 0) {
      B(right) = -B(right) - 1
      right -= 1
    }
  }

  var zeros = B.count(_ == 0)

  val newNegatives = B.count(_ < 0)
  if (newNegatives % 2 == 1) {
    zeros = if (zeros % 2 == 1) zeros else zeros - 1
  } else {
    zeros = if (zeros % 2 == 0) zeros else zeros - 1
  }
  if (zeros < 0) zeros = 0

  var i = 0
  while (zeros > 0) {
    if (B(i) == 0) {
      B(i) = -1
      zeros -= 1
    }
    i += 1
  }

  println(B.mkString(" "))
}

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  //val out: PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt).map(x => if (x >= 0) -x - 1 else x )
  if (a.foldLeft(0)((acc, x) => if (x < 0) acc + 1 else acc) % 2 == 1)
    a(0) = -a(0) - 1
  out.print(a.mkString(" "))
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    def nextDouble: Double = next.toDouble

    def nextLine: String = br.readLine
  }

}


object B515F extends App {

    def readNextLine : Array[Int] = {
      readLine.split(" ").map(_.toInt)
    }

    def becomeHappy (pair : (Int, Int), hg : Array[Int], hl: Array[Int], isHappy: Int) : Boolean = {
      def exist(arr : Array[Int], value : Int) : Int =
        arr.contains(value) match { case true => 1; case false => 0}
      (exist(hg, pair._1) + exist(hl, pair._2)) == isHappy
    }

    def isStuck(tg : List[(Int, Int)], hg : Array[Int], hl : Array[Int]) : Boolean = {
      tg.filter(pair =>
       becomeHappy(pair, hg, hl, 1) || becomeHappy(pair, hg, hl, 2) ).isEmpty
    }

    def B515F = {
      val l : Array[Int] = readNextLine
      val n = l(0)
      val m = l(1)
      val t = n * m
      var guys : List[Int] = Nil
      var gals : List[Int] = Nil

      for(i <- 0 until t) {
         guys ::= i % n
         gals ::= i % m
      }

      var together = guys.zip(gals).distinct

      var happyGuys : Array[Int] = (readNextLine) drop 1
      var happyGals : Array[Int] = (readNextLine) drop 1
      var willBeHappy : List[(Int, Int)] = Nil

      do {

        willBeHappy = together.filter(pair => becomeHappy(pair, happyGuys, happyGals, 1) || becomeHappy(pair, happyGuys, happyGals, 2))
        together = together.filter(pair => ! (becomeHappy(pair, happyGuys, happyGals, 1) || becomeHappy(pair, happyGuys, happyGals, 2)))
        happyGuys ++= willBeHappy.map(pair => pair._1)
        happyGals ++= willBeHappy.map(pair => pair._2)
      } while(!isStuck(together, happyGuys, happyGals) && !together.isEmpty)

       println(together.isEmpty match {case true => "Yes"; case false => "No"})
    }

 B515F

}

import java.util.Scanner

/**
 * Created by root on 2/21/15.
 */
object Drazil2 {

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

    val boys = Array.tabulate[Int](n)(_ => 0)
    val girls = Array.tabulate[Int](m)(_ => 0)

    (0 until sc.nextInt()) foreach { _ =>
      boys(sc.nextInt()) = 1
    }

    (0 until sc.nextInt()) foreach { _ =>
      girls(sc.nextInt()) = 1
    }

    val max = n*m

    for (i<- 0 to 2*max) {
      val b = i%n
      val g = i%m
      if (boys(b) == 1) {
        girls(g) = 1
      }
      if (girls(g) == 1){
        boys(b) = 1
      }
    }

    val ans = boys.filter(bf => bf ==0).size + girls.filter(gf => gf == 0).size
    if (ans == 0)
      println("Yes")
    else
      println("No")

  }

}

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object B515 extends App {

  def checkAllHappy(boys: Array[Boolean], girls: Array[Boolean]): Boolean = {
    boys.foreach((b) => {
      if (!b) {
        return false
      }
    })
    girls.foreach((b) => {
      if (!b) {
        return false
      }
    })
    true
  }

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val b: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val g: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val boys: Array[Boolean] = Array.ofDim[Boolean](n)
    val girls: Array[Boolean] = Array.ofDim[Boolean](m)
    for (i <- 0 until b.head) {
      boys(b(i+1)) = true
    }
    for (i <- 0 until g.head) {
      girls(g(i+1)) = true
    }

    for (i <- 0 until 100 * 100) {
      val boyId = i % n
      val girlId = i % m
      if (boys(boyId) || girls(girlId)) {
        boys(boyId) = true
        girls(girlId) = true
      }
    }

    if (checkAllHappy(boys, girls)) {
      println("Yes")
    } else {
      println("No")
    }
  }

  solve()

}

import java.util.Scanner

/**
 * Created by root on 2/21/15.
 */
object Drazil2 {

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

    val boys = Array.tabulate[Int](n)(_ => 0)
    val girls = Array.tabulate[Int](m)(_ => 0)

    (0 until sc.nextInt()) foreach { _ =>
      boys(sc.nextInt()) = 1
    }

    (0 until sc.nextInt()) foreach { _ =>
      girls(sc.nextInt()) = 1
    }

    val max = n*m

    for (i<- 0 until max) {
      val b = i%n
      val g = i%m
      if (boys(b) == 1) {
        girls(g) = 1
      }
      if (girls(g) == 1){
        boys(b) = 1
      }
    }

    val ans = boys.filter(bf => bf ==0).size + girls.filter(gf => gf == 0).size
    if (ans == 0)
      println("Yes")
    else
      println("No")

  }

}


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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = nal(N)
    val cum = cumSum(A)
    val L = nal(M)
    REP(M) { i =>
      val dorm = lowerBound(cum, L(i)) - 1
      out.println(s"${dorm + 1} ${L(i) - cum(dorm)}")
    }
  }

  // a >= x  [x-2, x-1, x, x, x, x+1] の 2
  def lowerBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  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[Long]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object CF_978C {
	def main(args: Array[String]) {
		val temp_nm = readLine().split(" ")
		val n = temp_nm(0).toInt
		val m = temp_nm(1).toInt

		val temp_a = readLine().split(" ")
		val a = for(x <- temp_a) yield(x.toLong)

		val temp_b = readLine().split(" ")
		var prefix_sum = 0l
		var p = 0

		for(x_str <- temp_b)
		{
			val x = x_str.toLong
			while(x - prefix_sum > a(p))
			{
				prefix_sum += a(p)
				p+=1
			}
			printf("%d %d\n",p+1,x-prefix_sum)
		}

	}
}

object problemA {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable
    import scala.util.control.Breaks._
    import scala.collection.JavaConverters._

    val source = System.in
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(n, m) = readArray().map(_.toInt)
        val a = readArray().map(_.toLong)
        val f = new Array[Long](n)
        f(0) = a(0)
        for (i <- 1 until n) f(i) = f(i - 1) + a(i)

        def find(k: Long): Int = {
            var (l, r) = (0, n - 1)
            var rs = 0
            while (l <= r) {
                val mid = (l + r) / 2
                if (f(mid) < k)
                    l = mid + 1
                else {
                    r = mid - 1
                    rs = mid
                }
            }
            rs
        }

        readArray().map(_.toLong).foreach(i => {
            val k = find(i)
            val t = if (k > 0) f(k - 1) else 0
            println(s"${k + 1} ${i - t}")
        })
    }
}


object B1556 {

  import scala.collection.mutable.ArrayBuffer

  /** TODO: Check! */
  private val multipleTests: Boolean = true

  def run(testNum: Int): Unit = {
    val n = int()
    val a = new ArrayBuffer[Int]()
    var even = 0
    var odd = 0
    for (_ <- 0 until n) {
      val x = int() % 2
      a += x
      if (x % 2 == 0)
        even += 1
      else
        odd += 1
    }
    if ((even - odd).abs > 1) {
      println(-1)
    } else {
      if (even > odd) {
        for (i <- 0 until n)
          a(i) = 1 - a(i)
      }
      var last = 0
      var ans: Long = 0
      for (i <- 0 until n) {
        if (a(i) == 1) {
          ans += (last - i).abs
          last += 2
        }
      }
      if (n % 2 == 0) {
        for (i <- 0 until n)
          a(i) = 1 - a(i)
        var secondAns: Long = 0
        var secondLast = 0
        for (i <- 0 until n) {
          if (a(i) == 1) {
            secondAns += (secondLast - i).abs
            secondLast += 2
          }
        }
        if (ans > secondAns) {
          println(secondAns)
        } else {
          println(ans)
        }
      } else {
        println(ans)
      }
    }
  }

  /** Template. */

  private val onlineJudge = System.getProperty("ONLINE_JUDGE") != null

  def main(args: Array[String]): Unit = {
    val t = if (multipleTests) reader.int() else 1
    (1 to t).foreach(run)
  }

  /** I/O. */

  import java.io._
  import java.nio.file._

  private val inputFileName = "input.txt"
  private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)

  private def string(): String = reader.string()
  private def int(): Int = reader.int()
  private def long(): Long = reader.long()
  private def double(): Double = reader.double()

  /** TODO: implement faster reader with buffer */
  /** TODO: implement writer */
  final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {
    import java.util.StringTokenizer

    def string(): String = next()
    def line(): String = tokenizer().get.nextToken("\n\r")
    def boolean(): Boolean = next().toBoolean
    def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def float(): Float = next().toFloat
    def double(): Double = next().toDouble
    def bigDecimal(): BigDecimal = BigDecimal(next())
    def lineNumber(): Int = linedDelegate.getLineNumber

    @inline def nextLine(): String = {
      current = None // reset the rest of current line
      delegate.readLine()
    }

    override def hasNext: Boolean = tokenizer().nonEmpty
    override def next(): String = tokenizer().getOrElse(throw new RuntimeException("End of input")).nextToken()
    override def close(): Unit = delegate.close()

    private lazy val linedDelegate = new LineNumberReader(delegate)
    private val tokenizers = Iterator.continually(delegate.readLine())
      .takeWhile(_ != null)
      .map(new StringTokenizer(_))
      .filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }
  }

  object FastReader {
    import scala.io.Codec

    def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)
    def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {
      Files.newBufferedReader(Paths.get(fileName), codec.charSet)
    }
    def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))
    def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {
      new BufferedReader(new InputStreamReader(inputStream, codec.charSet))
    }
  }
}

object B extends App {

  def swaps(an: IndexedSeq[Int]): Option[Int] = {
    val odds = an.indices.collect { case i if an(i) % 2 == 1 => i }

    def count(startIndex: Int): Int =
      (odds zip (startIndex to (an.length, 2))).foldLeft(0) { case (c, (j, i)) => c + math.abs(i - j) }

    (odds.length, an.length - odds.length) match {
      case (ol, el) if ol == el     => Some(count(0) min count(1))
      case (ol, el) if ol == el + 1 => Some(count(0))
      case (ol, el) if el == ol + 1 => Some(count(1))
      case _                        => None
    }
  }

  import scala.io.StdIn._

  val t = readInt()

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

    swaps(an) match {
      case Some(count) => println(count)
      case None        => println(-1)
    }
  }

}