You are given an array $$$a_1, a_2, \dots , a_n$$$ and two integers $$$m$$$ and $$$k$$$.You can choose some subarray $$$a_l, a_{l+1}, \dots, a_{r-1}, a_r$$$. The cost of subarray $$$a_l, a_{l+1}, \dots, a_{r-1}, a_r$$$ is equal to $$$\sum\limits_{i=l}^{r} a_i - k \lceil \frac{r - l + 1}{m} \rceil$$$, where $$$\lceil x \rceil$$$ is the least integer greater than or equal to $$$x$$$. The cost of empty subarray is equal to zero.For example, if $$$m = 3$$$, $$$k = 10$$$ and $$$a = [2, -4, 15, -3, 4, 8, 3]$$$, then the cost of some subarrays are:  $$$a_3 \dots a_3: 15 - k \lceil \frac{1}{3} \rceil = 15 - 10 = 5$$$;  $$$a_3 \dots a_4: (15 - 3) - k \lceil \frac{2}{3} \rceil = 12 - 10 = 2$$$;  $$$a_3 \dots a_5: (15 - 3 + 4) - k \lceil \frac{3}{3} \rceil = 16 - 10 = 6$$$;  $$$a_3 \dots a_6: (15 - 3 + 4 + 8) - k \lceil \frac{4}{3} \rceil = 24 - 20 = 4$$$;  $$$a_3 \dots a_7: (15 - 3 + 4 + 8 + 3) - k \lceil \frac{5}{3} \rceil = 27 - 20 = 7$$$. Your task is to find the maximum cost of some subarray (possibly empty) of array $$$a$$$.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 3 \cdot 10^5, 1 \le m \le 10, 1 \le k \le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).

Print the maximum cost of some subarray of array $$$a$$$.

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


Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends j - i + 1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons?

The first line contains three integers n, m and k (1 ≤ n, m ≤ 500, 0 ≤ k ≤ 500) — the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson).

Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons.

NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day.

object D extends App {

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

  val Array(n, m, k) = readInts(3)

  val days = Array.fill(n){ readLine }

  val dp = Array.fill(n, k + 1)(Int.MaxValue / 2)

  for {
    d <- 0 until n
  } {
    val day = days(d)
    var skipBefore = 0
    var start = 0
    val minThisDay = Array.fill(k + 1)(m + 1)

    while (start < m) {
      while (start < m && day(start) == '0') start += 1
      var skipAfter = 0
      var end = m - 1
      while (end >= start) {
        while (end >= start && day(end) == '0') end -= 1
        //println(day, start, skipBefore, end, skipAfter)
        val skipped = skipBefore + skipAfter
        val hours = end - start + 1
        if (skipped <= k && hours < minThisDay(skipped)) minThisDay(skipped) = hours
        if (end >= start) {
          skipAfter += 1
          end -= 1
        }
      }
      val skipped = skipBefore + skipAfter
      if (skipped <= k) minThisDay(skipped) = 0
      if (start < m) {
        skipBefore += 1
        start += 1
      }
    }
    if (d == 0) dp(d) = minThisDay
    else {
      var k1 = 0
      while (k1 <= k) {
        var k2 = 0
        while (k2 + k1 <= k) {
          dp(d)(k1 + k2) = Math.min(dp(d)(k1 + k2), dp(d - 1)(k1) + minThisDay(k2))
          k2 += 1
        }
        k1 += 1
      }
    }
    //println(dp(d).mkString(" "), minThisDay.mkString(" "))
  }

  println(dp(n - 1).min)
}


Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as aij. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that aij = apq at (i, j) ≠ (p, q).Dima has already written a song — a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).We'll represent a way to play a song as a sequence of pairs (xi, yi) (1 ≤ i ≤ s), such that the xi-th string on the yi-th fret produces the i-th note from the song. The complexity of moving between pairs (x1, y1) and (x2, y2) equals  + . The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!

The first line of the input contains four integers n, m, k and s (1 ≤ n, m ≤ 2000, 1 ≤ k ≤ 9, 2 ≤ s ≤ 105).  Then follow n lines, each containing m integers aij (1 ≤ aij ≤ k). The number in the i-th row and the j-th column (aij) means a note that the guitar produces on the i-th string and the j-th fret. The last line of the input contains s integers qi (1 ≤ qi ≤ k) — the sequence of notes of the song.

In a single line print a single number — the maximum possible complexity of the song.

import scala.collection._

object E extends App {

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

  val Array(n, m, k, s) = readInts(4)
  val as = Array.fill(n) { readLine }
  val qs = readInts(s)

  def D1(x: Int, y: Int) = x + y
  def D2(x: Int, y: Int) = x - y

  val minD1, minD2 = Array.fill(k) { Int.MaxValue / 2 }
  val maxD1, maxD2 = Array.fill(k) { Int.MinValue / 2 }

  val maxD = Array.fill(k, k) { 0 }
  val seen = mutable.BitSet()

  var i = 0
  while (i < n) {
    var j = 0
    while (j < m) {
      val a = as(i)(2 * j) - '1'
      seen(a) = true
      val d1 = D1(i, j)
      val d2 = D2(i, j)
      minD1(a) = Math.min(minD1(a), d1)
      maxD1(a) = Math.max(maxD1(a), d1)
      minD2(a) = Math.min(minD2(a), d2)
      maxD2(a) = Math.max(maxD2(a), d2)

      var u = 0
      while (u < k) {
        if (seen(u)) {
          val max = Math.max(Math.max(Math.abs(minD1(u) - d1), Math.abs(maxD1(u) - d1)),
            Math.max(Math.abs(minD2(u) - d2), Math.abs(maxD2(u) - d2)))
          maxD(a)(u) = Math.max(maxD(a)(u), max)
          maxD(u)(a) = maxD(a)(u)
        }
        u += 1
      }

      j += 1
    }
    i += 1
  }

  var prev = qs(0)
  var ans = 0
  for (q <- qs.drop(1)) {
    if (maxD(prev - 1)(q - 1) > ans) {
      ans = maxD(prev - 1)(q - 1)
    }
    prev = q
  }

  println(ans)
}


A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.The traffic light on the crosswalk from the j-th house of the i-th row to the (j + 1)-th house of the same row has waiting time equal to aij (1 ≤ i ≤ 2, 1 ≤ j ≤ n - 1). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals bj (1 ≤ j ≤ n). The city doesn't have any other crossings.The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing.    Figure to the first sample. Help Laurenty determine the minimum total time he needs to wait at the crossroads.

The first line of the input contains integer n (2 ≤ n ≤ 50) — the number of houses in each row.  Each of the next two lines contains n - 1 space-separated integer — values aij (1 ≤ aij ≤ 100).  The last line contains n space-separated integers bj (1 ≤ bj ≤ 100).

Print a single integer — the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.

NoteThe first sample is shown on the figure above. In the second sample, Laurenty's path can look as follows:   Laurenty crosses the avenue, the waiting time is 3;  Laurenty uses the second crossing in the first row, the waiting time is 2;  Laurenty uses the first crossing in the first row, the waiting time is 1;  Laurenty uses the first crossing in the first row, the waiting time is 1;  Laurenty crosses the avenue, the waiting time is 1;  Laurenty uses the second crossing in the second row, the waiting time is 3.  In total we get that the answer equals 11.In the last sample Laurenty visits all the crossings, so the answer is 4.

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

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)

  }
}


Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.

The first line of input contains three integers n, m and q (2 ≤ n ≤ 105, 1 ≤ m, q ≤ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations. The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary. Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi. Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered. All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.

First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes). After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3. See the samples for better understanding.

3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like

8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou

import scala.io.StdIn.readLine

object MadmudAndDictionary extends App{
  case class ParentRef(order: Int, set: DSet, negate: Boolean) {
    def ^(relation: Boolean) = copy(negate = negate ^ relation)
    def upgrade = copy(order = order + 1)
  }

  class DSet {
    var ref = ParentRef(0, this, negate = false)

    def upgrade() = ref = ref.upgrade

    def parent: ParentRef =
      if (ref.set == this) ref
      else {
        ref = ref.set.parent ^ ref.negate
        ref
      }

    def union(that: DSet, negate: Boolean): Boolean = {
      val thisParent = this.parent
      val thatParent = that.parent
      if (thisParent.order > thatParent.order) that.union(this, negate)
      else if (thisParent.set == thatParent.set) !thisParent.negate ^ thatParent.negate ^ negate
      else {
        parent.set.ref = that.parent.copy() ^ (negate ^ parent.negate)
        if (thisParent.order == thatParent.order) thatParent.set.upgrade()
        true
      }
    }

    def query(that: DSet) =
      if (this.parent.set != that.parent.set) 3
      else if (this.parent.negate ^ that.parent.negate) 2
      else 1
  }

  val Array(n, m, q) = readLine().split(' ').map(_.toInt)
  val sets = readLine().split(' ').map(_ → new DSet).toMap
  for (_ ← 1 to m) {
    val Array(op, left, right) = readLine().split(' ')
    println(if (sets(left).union(sets(right), op == "2")) "YES" else "NO")
  }
  for (_ ← 1 to q) {
    val Array(left, right) = readLine().split(' ')
    println(sets(left).query(sets(right)))
  }
}


An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.

The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$ — the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.

NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime.

import java.io._
import java.math.BigInteger
import java.util.StringTokenizer

import scala.annotation.tailrec

object E {
  def solve(in: Input, out: PrintWriter): Unit = {
    val (primes, nonPrime) = makeSieve(100000)
    val myPrimes = new Array[Int](primes.length)
    for (_ <- 0 until in.nextInt()) {
      val v = in.nextInt()
      val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)
      if (firstPrimeIndex == -1) {
        println(s"$v is prime")
      } else {
        val firstPrime = primes(firstPrimeIndex)
        val rest = v / firstPrime
        if (BigInteger.valueOf(rest).isProbablePrime(25)) {
          // v is p1 * p2
          if (rest == firstPrime) {
            // easy
            out.println(firstPrime + " " + v)
            out.println(0)
          } else {
            out.println(firstPrime + " " + rest + " " + v)
            out.println(1)
          }
        } else {
          var primeCount = 1
          myPrimes(0) = firstPrime
          var tmp = drain(v, firstPrime)
          var primeIndex = firstPrimeIndex + 1
          while (primeIndex < primes.length && tmp > 1) {
            val pp = primes(primeIndex)
            primeIndex += 1
            if (tmp % pp == 0) {
              myPrimes(primeCount) = pp
              primeCount += 1
              tmp = drain(tmp, pp)
            }
          }
          if (tmp > 1) {
            myPrimes(primeCount) = tmp
            primeCount += 1
          }
          val used = new scala.collection.mutable.HashSet[Int]
          used.add(1)
          val lists = Array.fill(primeCount)(Array.newBuilder[Int])
          val postLists = new Array[Int](primeCount)
          for (i <- 0 until primeCount) {
            lists(i) += myPrimes(i)
            used.add(myPrimes(i))
            val nv = myPrimes(i) * myPrimes((i + 1) % primeCount)
            if (used.contains(nv)) {
              postLists(i) = v
              used.add(v)
            } else {
              postLists(i) = nv
              used.add(nv)
            }
          }

          var divisor = 1
          while (divisor <= v / divisor) {
            if (v % divisor == 0) {
              if (!used.contains(divisor)) {
                lists(findIndex(divisor, myPrimes, 0)) += divisor
                used.add(divisor)
              }
              val another = v / divisor
              if (!used.contains(another)) {
                lists(findIndex(another, myPrimes, 0)) += another
                used.add(another)
              }
            }
            divisor += 1
          }

          for (i <- 0 until primeCount) lists(i) += postLists(i)

          out.println(lists.flatMap(_.result()).mkString(" "))
          out.println(0)
        }
      }
    }
  }

  @tailrec
  private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int = {
    if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)
  }

  @tailrec
  private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("3\n6\n4\n30", "2 3 6\n1\n2 4\n0\n2 30 6 3 15 5 10\n0", "Sample"),
    ("1\n12", "2 4 6 3 12\n0", "Tricky case 1"),
    ("1\n2000006", "2 1000003 2000006\n1", "Special #1"),
    ("1\n4000012", "2 4 2000006 1000003 4000012\n0", "Special #2"),
  )

  def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {
    val nonPrime = new Array[Boolean](limit + 1)
    val builder = Array.newBuilder[Int]
    var i = 2
    while (i <= limit) {
      if (!nonPrime(i)) {
        builder += i
        var j = 2 * i
        while (j <= limit) {
          nonPrime(j) = true
          j += i
        }
      }
      i += 1
    }
    (builder.result(), nonPrime)
  }

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}

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

import scala.annotation.tailrec

object E {
  def solve(in: Input, out: PrintWriter): Unit = {
    val (primes, nonPrime) = makeSieve(100000)
    val myPrimes = new Array[Int](primes.length)
    for (_ <- 0 until in.nextInt()) {
      val v = in.nextInt()
      val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)
      if (firstPrimeIndex == -1) {
        println(s"$v is prime")
      } else {
        val firstPrime = primes(firstPrimeIndex)
        val rest = v / firstPrime
        if (rest < nonPrime.length && !nonPrime(rest)) {
          // v is p1 * p2
          if (rest == firstPrime) {
            // easy
            out.println(firstPrime + " " + v)
            out.println(0)
          } else {
            out.println(firstPrime + " " + rest + " " + v)
            out.println(1)
          }
        } else {
          var primeCount = 1
          myPrimes(0) = firstPrime
          var tmp = drain(v, firstPrime)
          var primeIndex = firstPrimeIndex + 1
          while (primeIndex < primes.length && tmp > 1) {
            val pp = primes(primeIndex)
            primeIndex += 1
            if (tmp % pp == 0) {
              myPrimes(primeCount) = pp
              primeCount += 1
              tmp = drain(tmp, pp)
            }
          }
          if (tmp > 1) {
            myPrimes(primeCount) = tmp
            primeCount += 1
          }
          val used = new scala.collection.mutable.HashSet[Int]
          used.add(1)
          val lists = Array.fill(primeCount)(Array.newBuilder[Int])
          val postLists = new Array[Int](primeCount)
          for (i <- 0 until primeCount) {
            lists(i) += myPrimes(i)
            used.add(myPrimes(i))
            val nv = myPrimes(i) * myPrimes((i + 1) % primeCount)
            if (used.contains(nv)) {
              postLists(i) = v
              used.add(v)
            } else {
              postLists(i) = nv
              used.add(nv)
            }
          }

          var divisor = 1
          while (divisor <= v / divisor) {
            if (v % divisor == 0) {
              if (!used.contains(divisor)) {
                lists(findIndex(divisor, myPrimes, 0)) += divisor
                used.add(divisor)
              }
              val another = v / divisor
              if (!used.contains(another)) {
                lists(findIndex(another, myPrimes, 0)) += another
                used.add(another)
              }
            }
            divisor += 1
          }

          for (i <- 0 until primeCount) lists(i) += postLists(i)

          out.println(lists.flatMap(_.result()).mkString(" "))
          out.println(0)
        }
      }
    }
  }

  @tailrec
  private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int = {
    if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)
  }

  @tailrec
  private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("3\n6\n4\n30", "2 3 6\n1\n2 4\n0\n2 30 6 3 15 5 10\n0", "Sample"),
    ("1\n12", "2 4 6 3 12\n0", "Tricky case 1")
  )

  def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {
    val nonPrime = new Array[Boolean](limit + 1)
    val builder = Array.newBuilder[Int]
    var i = 2
    while (i <= limit) {
      if (!nonPrime(i)) {
        builder += i
        var j = 2 * i
        while (j <= limit) {
          nonPrime(j) = true
          j += i
        }
      }
      i += 1
    }
    (builder.result(), nonPrime)
  }

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}

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

import scala.annotation.tailrec

object E {
  def solve(in: Input, out: PrintWriter): Unit = {
    val (primes, nonPrime) = makeSieve(100000)
    val myPrimes = new Array[Int](primes.length)
    for (_ <- 0 until in.nextInt()) {
      val v = in.nextInt()
      val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)
      val firstPrime = primes(firstPrimeIndex)
      val rest = v / firstPrime
      if (rest < nonPrime.length && !nonPrime(rest)) {
        // v is p1 * p2
        if (rest == firstPrime) {
          // easy
          out.println(firstPrime + " " + v)
          out.println(0)
        } else {
          out.println(firstPrime + " " + rest + " " + v)
          out.println(1)
        }
      } else {
        var primeCount = 1
        myPrimes(0) = firstPrime
        var tmp = drain(v, firstPrime)
        var primeIndex = firstPrimeIndex
        while (tmp > 1) {
          primeIndex += 1
          val pp = primes(primeIndex)
          if (tmp % pp == 0) {
            myPrimes(primeCount) = pp
            primeCount += 1
            tmp = drain(tmp, pp)
          }
        }
        val used = new scala.collection.mutable.HashSet[Int]
        used.add(1)
        val lists = Array.fill(primeCount)(Array.newBuilder[Int])
        for (i <- 0 until primeCount) {
          lists(i) += myPrimes(i)
          used.add(myPrimes(i))
          val nv = myPrimes(i) * myPrimes((i + 1) % primeCount)
          lists(i) += nv
          used.add(nv)
        }

        var divisor = 1
        while (divisor <= v / divisor) {
          if (v % divisor == 0) {
            if (!used.contains(divisor)) {
              lists(findIndex(divisor, myPrimes, 0)) += divisor
              used.add(divisor)
            }
            val another = v / divisor
            if (!used.contains(another)) {
              lists(findIndex(another, myPrimes, 0)) += another
              used.add(another)
            }
          }
          divisor += 1
        }

        out.println(lists.flatMap(_.result()).mkString(" "))
        out.println(0)
      }
    }
  }

  @tailrec
  private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int = {
    if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)
  }

  @tailrec
  private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("3\n6\n4\n30", "2 3 6\n1\n2 4\n0\n2 6 30 3 15 5 10\n0", "Sample"),
  )

  def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {
    val nonPrime = new Array[Boolean](limit + 1)
    val builder = Array.newBuilder[Int]
    var i = 2
    while (i <= limit) {
      if (!nonPrime(i)) {
        builder += i
        var j = 2 * i
        while (j <= limit) {
          nonPrime(j) = true
          j += i
        }
      }
      i += 1
    }
    (builder.result(), nonPrime)
  }

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}

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

import scala.annotation.tailrec

object E {
  def solve(in: Input, out: PrintWriter): Unit = {
    val (primes, nonPrime) = makeSieve(100000)
    val myPrimes = new Array[Int](primes.length)
    for (_ <- 0 until in.nextInt()) {
      val v = in.nextInt()
      val firstPrimeIndex = primes.indices.indexWhere(i => v % primes(i) == 0)
      val firstPrime = primes(firstPrimeIndex)
      val rest = v / firstPrime
      if (rest < nonPrime.length && !nonPrime(rest)) {
        // v is p1 * p2
        if (rest == firstPrime) {
          // easy
          out.println(firstPrime + " " + v)
          out.println(0)
        } else {
          out.println(firstPrime + " " + rest + " " + v)
          out.println(1)
        }
      } else {
        var primeCount = 1
        myPrimes(0) = firstPrime
        var tmp = drain(v, firstPrime)
        var primeIndex = firstPrimeIndex
        while (tmp > 1) {
          primeIndex += 1
          val pp = primes(primeIndex)
          if (tmp % pp == 0) {
            myPrimes(primeCount) = pp
            primeCount += 1
            tmp = drain(tmp, pp)
          }
        }
        val lists = Array.fill(primeCount)(Array.newBuilder[Int])
        for (i <- 0 until primeCount) lists(i) += myPrimes(i)

        var divisor = 1
        while (divisor <= v / divisor) {
          if (v % divisor == 0) {
            if (nonPrime(divisor)) {
              lists(findIndex(divisor, myPrimes, 0)) += divisor
            }
            val another = v / divisor
            if (another != divisor) {
              lists(findIndex(another, myPrimes, 0)) += another
            }
          }
          divisor += 1
        }

        out.println(lists.flatMap(_.result()).mkString(" "))
        out.println(0)
      }
    }
  }

  @tailrec
  private def findIndex(v: Int, myPrimes: Array[Int], i: Int): Int =
    if (v % myPrimes(i) == 0) i else findIndex(v, myPrimes, i + 1)

  @tailrec
  private def drain(v: Int, p: Int): Int = if (v % p == 0) drain(v / p, p) else v

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("3\n6\n4\n30", "2 3 6\n1\n2 4\n0\n2 30 10 6 3 15 5\n0", "Sample"),
  )

  def makeSieve(limit: Int): (Array[Int], Array[Boolean]) = {
    val nonPrime = new Array[Boolean](limit + 1)
    val builder = Array.newBuilder[Int]
    var i = 2
    while (i <= limit) {
      if (!nonPrime(i)) {
        builder += i
        var j = 2 * i
        while (j <= limit) {
          nonPrime(j) = true
          j += i
        }
      }
      i += 1
    }
    (builder.result(), nonPrime)
  }

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}


Mahmoud and Ehab are in the fourth stage now.Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length n, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.Help Mahmoud and Ehab find these two positions.You will get Wrong Answer verdict if   Your queries doesn't satisfy interaction protocol described below.  You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query.  Your final answer is not correct.  You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .

The first line of input will contain a single integer n (2 ≤ n ≤ 1000) — the length of the hidden binary string.

To print the final answer, print "! pos0 pos1" (without quotes), where pos0 and pos1 are positions of some '0' and some '1' in the string (the string is 1-indexed). Don't forget to flush the output after printing the answer!

NoteHamming distance definition: https://en.wikipedia.org/wiki/Hamming_distanceIn the first test case the hidden binary string is 101, The first query is 000, so the Hamming distance is 2. In the second query the hidden string is still 101 and query is 001, so the Hamming distance is 1.After some queries you find that symbol at position 2 is '0' and symbol at position 1 is '1', so you print "! 2 1".

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)

  def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1

  def question(query: IndexedSeq[Int]): Int = {
    println(s"? ${query.mkString("")}")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - all

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (t == m - l + 1) guess(m + 1, r, l, pos1)
      else if (t == l - m - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  val n = scala.io.StdIn.readLine().toInt
  val all = question(query)
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)

  def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1

  def question(query: IndexedSeq[Int]): Int = {
    println(s"? ${query.mkString("")}")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - all

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (t == r - l + 1) guess(m + 1, r, l, pos1)
      else if (t == l - r - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  val n = scala.io.StdIn.readLine().toInt
  val all = question(query)
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)

  def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1

  def question(query: IndexedSeq[Int]): Int = {
    println(s"? ${query.mkString("")}")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 2
      val t = zero(l, m)
      if (t == m - l + 1) guess(m + 1, r, l, pos1)
      else if (t == l - m - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  /**
    * 2 ≤ n ≤ 1000
    */
  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: IndexedSeq[Byte] = IndexedSeq.fill(n)(1)

  def query(l: Long, r: Long): IndexedSeq[Byte] = for (i <- 1 to n) yield if (i >= l && i <= r) 0:Byte else 1:Byte

  def question(query: IndexedSeq[Byte]): Long = {
    println(s"? ${query.mkString("")}")
    Console.flush()
    n - scala.io.StdIn.readLine().toLong
  }

  def answer(pos: (Long, Long)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Long, r: Long): Long = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Long, r: Long, pos0: Long = 0, pos1: Long = 0): (Long, Long) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (pos0 == 0 && t == m - l + 1) guess(m + 1, r, l, pos1)
      else if (pos1 == 0 && t == l - m - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  /**
    * 2 ≤ n ≤ 1000
    */
  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: IndexedSeq[Byte] = IndexedSeq.fill(n)(1)

  def query(l: Long, r: Long): IndexedSeq[Byte] = for (i <- 1 to n) yield if (i >= l && i <= r) 0:Byte else 1:Byte

  def question(query: IndexedSeq[Byte]): Long = {
    println(s"? ${query.mkString("")}")
    Console.flush()
    n - scala.io.StdIn.readLine().toLong
  }

  def answer(pos: (Long, Long)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Long, r: Long): Long = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Long, r: Long, pos0: Long = 0, pos1: Long = 0): (Long, Long) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (t == m - l + 1) guess(m + 1, r, l, pos1)
      else if (t == l - m - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  /**
    * 2 ≤ n ≤ 1000
    */
  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: String = "1" * n

  def query(l: Int, r: Int): String = "1" * (l - 1) + "0" * (r - l + 1) + "1" * (n - r)

  def question(query: String): Int = {
    println(s"? $query")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (pos0 == 0 && t == r - l + 1) guess(m + 1, r, l, pos1)
      else if (pos1 == 0 && t == l - r - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  /**
    * 2 ≤ n ≤ 1000
    */
  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: IndexedSeq[Int] = IndexedSeq.fill(n)(1)

  def query(l: Int, r: Int): IndexedSeq[Int] = for (i <- 1 to n) yield if (i >= l && i <= r) 0 else 1

  def question(query: IndexedSeq[Int]): Int = {
    println(s"? ${query.mkString("")}")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (t == m - l + 1) guess(m + 1, r, l, pos1)
      else if (t == l - m - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: String = "1" * n

  def query(l: Int, r: Int): String = "1" * (l - 1) + "0" * (r - l + 1) + "1" * (n - r)

  def question(query: String): Int = {
    println(s"? $query")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (t == r - l + 1) guess(m + 1, r, l, pos1)
      else if (t == l - r - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  /**
    * 2 ≤ n ≤ 1000
    */
  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}

import scala.annotation.tailrec

/**
  * @see http://codeforces.com/contest/862/problem/D
  *      Based on http://codeforces.com/profile/mahmoudbadawy, https://pastebin.com/RMyLDMxw
  */

object DMahmoudAndEhabAndTheBinaryString extends App {
  def query: String = "1" * n

  def query(l: Int, r: Int): String = "1" * (l - 1) + "0" * (r - l + 1) + "1" * (n - r)

  def question(query: String): Int = {
    println(s"? $query")
    Console.flush()
    n - scala.io.StdIn.readLine().toInt
  }

  def answer(pos: (Int, Int)): Unit = {
    println(s"! ${pos._1} ${pos._2}")
    Console.flush()
  }

  def zero(l: Int, r: Int): Int = question(query(l, r)) - question(query)

  @tailrec
  def guess(l: Int, r: Int, pos0: Int = 0, pos1: Int = 0): (Int, Int) = {
    if (pos0 > 0 && pos1 > 0) (pos0, pos1)
    else {
      val m = (r + l) >> 1
      val t = zero(l, m)
      if (pos0 == 0 && t == m - l + 1) guess(m + 1, r, l, pos1)
      else if (pos1 == 0 && t == l - m - 1) guess(m + 1, r, pos0, l)
      else guess(l, m, pos0, pos1)
    }
  }

  /**
    * 2 ≤ n ≤ 1000
    */
  val n = scala.io.StdIn.readLine().toInt
  answer(guess(1, n))
}


The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!

The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).

import java.util.StringTokenizer

object M extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val k = int()

  val ans = readLine().split(' ').map(_.toInt).sorted.take(k).sum

  println(ans)
}