import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val arr: Array[Int] = Array.fill(n)(sc.nextInt())

    val (sortedArr, gList, m, cnt) = shellSort(arr)
    println(m)
    println(gList.toList.take(m).mkString(" "))
    println(cnt)
    sortedArr.foreach(println)
  }

  def insertionSort(arr: Array[Int], g: Int): (Array[Int], Int) = {
    val ret = arr.clone()
    var cnt = 0

    for((v, i) <- ret.zipWithIndex) {
      var j = i - g
      while(j >= 0 && ret(j) > v) {
        ret(j + g) = ret(j)
        cnt += 1
        j -= g
      }
      ret(j + g) = v
    }

    return (ret, cnt)
  }

  def shellSort(arr: Array[Int]): (Array[Int], Array[Int], Int, Int) = {
    var ret: Array[Int] = arr.clone()
    val gList = Array.fill(ret.length)(-1)
    var cnt = 0

    var g = arr.length / 2
    var m = 0
    while(g > 0) {
      gList(m) = g
      var (sortedArr, c) = insertionSort(ret, g)
      ret = sortedArr
      g = g / 2
      m += 1
      cnt += c
    }

    return (ret, gList, m, cnt)
  }
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Shell Sort

Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.

1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])

A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.

Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:

$1 \leq m \leq 100$

$0 \leq G_i \leq n$

cnt does not exceed $\lceil n^{1.5}\rceil$

Input

In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.

Output

In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.

In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.

This problem has multiple solutions and the judge will be performed by a special validator.

Constraints

$1 \leq n \leq 1,000,000$

$0 \leq A_i \leq 10^9$

Sample Input 1

5
5
1
4
3
2

Sample Output 1

2
4 1
3
1
2
3
4
5

Sample Input 2

3
3
2
1

Sample Output 2

1
1
3
1
2
3

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import scala.io.StdIn.readInt

object Main {

  def insertionSort(a:Array[Int],n:Int,g:Int):Int = {
    var cnt = 0
    for(i <- g until n) {
      val v = a(i)
      var j = i-g
      while( j>=0 && a(j) > v ) {
        a(j+g) = a(j)
        j = j-g
        cnt += 1
      }
      a(j+g) = v
    }
    cnt
  }

  def getG(g:List[Int],x:Double,n:Double):List[Int] = {
    val y = x*2.25+1
    if(y > n) g
    else
      getG(Math.ceil(y).toInt::g,y,n)
  }

  def main(args:Array[String]) = {
    val n = readInt
    val a = (for(i <- 0 until n) yield readInt).toArray
    val g = getG(List(),0,n.toDouble)
    val m = g.length
    var ct = 0

    for(i <- g) {
      ct += insertionSort(a,n,i)
    }
    println(m)
    println(g.mkString(" "))
    println(ct)
    println(a.mkString("\n"))
  }
}


import scala.io.StdIn.{readLong, readLine}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val arr = (1 to len).toArray.map(a => readLong)
        shellSort(arr, len).mkString("\n")
    }

    def shellSort(arr: Array[Long], len: Int): Array[Long] = {
        val copy = new Array[Long](len)
        arr.copyToArray(copy)
        var cnt = 0
        val groups = genGroups(len).reverse
        println(groups.length + "\n" + groups.mkString(" "))
        groups.foreach { g =>
            (0 until g).foreach { start =>
                cnt += insertionSort(copy, start, len, g)
            }
        }
        println(cnt)
        copy
    }

    def insertionSort(arr: Array[Long], start: Int, len: Int, group: Int): Int = {
        var cnt = 0
         Range(start, len, group).foreach { targetIndex =>
             val target = arr(targetIndex)
             Range(start, targetIndex, group).reverse.find { insertIndex =>
                 if (arr(insertIndex) > target) {
                     arr(insertIndex + group) = arr(insertIndex)
                     arr(insertIndex) = target
                     cnt += 1
                     false
                 } else {
                     true
                 }
             }
         }
        cnt
    }

    def genGroups(len: Int): List[Int] =  {
        def go(len: Int, glen: Int, next: Int): List[Int] = next match {
            case a if (a == 1) || (a < len && glen < (len / 9)) => a :: go(len, glen + 1, a * 3 + 1)
            case a => Nil
        }
        go(len, 0, 1)
    }

}


import scala.io.StdIn.{readLong, readLine}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val arr = (1 to len).toArray.map(a => readLong)
        shellSort(arr, len).mkString("\n")
    }

    def shellSort(arr: Array[Long], len: Int): Array[Long] = {
        val copy = new Array[Long](len)
        arr.copyToArray(copy)
        var cnt = 0
        val groups = genGroups(len).reverse
        println(groups.length + "\n" + groups.mkString(" "))
        groups.foreach { g =>
            (0 until g).foreach { start =>
                cnt += insertionSort(copy, start, len, g)
            }
        }
        println(cnt)
        copy
    }

    def insertionSort(arr: Array[Long], start: Int, len: Int, group: Int): Int = {
        var cnt = 0
         Range(start, len, group).foreach { targetIndex =>
             val target = arr(targetIndex)
             Range(start, targetIndex, group).reverse.find { insertIndex =>
                 if (arr(insertIndex) > target) {
                     arr(insertIndex + group) = arr(insertIndex)
                     arr(insertIndex) = target
                     cnt += 1
                     false
                 } else {
                     true
                 }
             }
         }
        cnt
    }

    def genGroups(len: Int): List[Int] =  {
        def go(len: Int, glen: Int, next: Int): List[Int] = next match {
            case a if (a == 1) || (a < len && glen < len) => a :: go(len, glen + 1, a * 3 + 1)
            case a => Nil
        }
        go(len, 0, 1)
    }
}


import scala.io.StdIn.{readLong, readInt}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val arr = (1 to len).toArray.map(a => readLong)
        println(shellSort(arr, len).mkString("\n"))
    }

    def shellSort(arr: Array[Long], len: Int): Array[Long] = {
        val copy = new Array[Long](len)
        arr.copyToArray(copy)
        var cnt = 0
        val groups = genGroups(len).reverse
        println(groups.length + "\n" + groups.mkString(" "))
        for (g <- groups) {
            for (start <- (0 until g)) {
                cnt += insertionSort(copy, start, len, g)
            }
        }
        println(cnt)
        copy
    }

    def insertionSort(arr: Array[Long], start: Int, len: Int, group: Int): Int = {
        var cnt = 0
        def insert(target: Long, ptr: Int): Unit = ptr match {
            case a if (a < 0 || arr(ptr) <= target) => arr(ptr + group) = target
            case a => {
                cnt += 1
                arr(ptr + group) = arr(ptr)
                insert(target, ptr - group)
            }
        }
        for (targetIndex <- Range(start, len, group)) { insert(arr(targetIndex), targetIndex - group)}
        cnt
    }

    def genGroups(len: Int): List[Int] =  {
        def go(len: Int, glen: Int, next: Int): List[Int] = next match {
            case a if (a == 1) || (a < len && glen < len) => a :: go(len, glen + 1, a * 3 + 1)
            case a => Nil
        }
        go(len, 0, 1)
    }
}


import scala.io.StdIn.{readLong, readInt}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val arr = (1 to len).toArray.map(a => readLong)
        println(shellSort(arr, len).mkString("\n"))
    }

    def shellSort(arr: Array[Long], len: Int): Array[Long] = {
        val copy = new Array[Long](len)
        arr.copyToArray(copy)
        var cnt = 0
        val groups = genGroups(len).reverse
        println(groups.length + "\n" + groups.mkString(" "))
        for (g <- groups) {
            cnt += insertionSort(copy, len, g)
        }
        println(cnt)
        copy
    }

    def insertionSort(arr: Array[Long], len: Int, group: Int): Int = {
        var cnt = 0
        def insert(target: Long, ptr: Int): Unit = ptr match {
            case a if (a < 0 || arr(ptr) <= target) => arr(ptr + group) = target
            case a => {
                cnt += 1
                arr(ptr + group) = arr(ptr)
                insert(target, ptr - group)
            }
        }
        for (targetIndex <- (0 until len)) { insert(arr(targetIndex), targetIndex - group)}
        cnt
    }

    def genGroups(len: Int): List[Int] =  {
        def go(len: Int, glen: Int, next: Int): List[Int] = next match {
            case a if (a == 1) || (a < len && glen < len) => a :: go(len, glen + 1, a * 3 + 1)
            case a => Nil
        }
        go(len, 0, 1)
    }
}


import scala.io.StdIn.{readInt, readLong};

object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val arr = (0 until n).map(a => readLong).toArray;
        val interval = fetchInterval(n);
        val cnt = shellSort(arr, n, interval);
        println(interval.length);
        println(interval.mkString(" "));
        println(cnt);
        println(arr.mkString("\n"));
    }

    def fetchInterval(n: Int): List[Int] = {
        val len = n;
        def go(g: Int, ret: List[Int]): List[Int] = {
            val ng = (g * 3) + 1;
            if (ng < len) go(ng, ng :: ret) else ret;
        }
        go(1, List(1));
    }

    def shellSort(arr: Array[Long], n: Int, interval: List[Int]): Int = {
        interval.foldLeft(0) { (cnt, i) =>
            (0 until n).foldLeft(cnt) { (cnt, j) =>
                insertionSort(arr, j, i) + cnt;
            }
        }
    }

    def insertionSort(arr: Array[Long], index: Int, interval: Int): Int = {
        val insert = arr(index);
        var cnt = 0;
        def go(curr: Int): Unit = {
            val prev = curr - interval;
            if (prev < 0 || arr(prev) <= insert) {
                arr(curr) = insert;
            } else {
                arr(curr) = arr(prev);
                cnt += 1;
                go(prev);
            }
        }
        go(index);
        cnt
    }
}


import scala.io.StdIn.{readInt, readLong};

object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val arr = (0 until n).map(a => readLong).toArray;
        val interval = fetchInterval(n);
        val cnt = shellSort(arr, n, interval);
        println(interval.length);
        println(interval.mkString(" "));
        println(cnt);
        println(arr.mkString("\n"));
    }

    def fetchInterval(n: Int): List[Int] = {
        val len = n / 9;
        def go(g: Int, ret: List[Int]): List[Int] = {
            val ng = (g * 3) + 1;
            if (ng < len) go(ng, ng :: ret) else ret;
        }
        go(1, List(1));
    }

    def shellSort(arr: Array[Long], n: Int, interval: List[Int]): Int = {
        interval.foldLeft(0) { (cnt, i) =>
            (0 until n).foldLeft(cnt) { (cnt, j) =>
                insertionSort(arr, j, i) + cnt;
            }
        }
    }

    def insertionSort(arr: Array[Long], index: Int, interval: Int): Int = {
        val insert = arr(index);
        var cnt = 0;
        def go(curr: Int): Unit = {
            val prev = curr - interval;
            if (prev < 0 || arr(prev) <= insert) {
                arr(curr) = insert;
            } else {
                arr(curr) = arr(prev);
                cnt += 1;
                go(prev);
            }
        }
        go(index);
        cnt
    }
}


object Main {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt()
    val seq: Seq[Long] = {
      for (i <- 1 to n) yield {
        scala.io.StdIn.readLong()
      }
    }.toList
    val (retSeq, g, cnt) = seq.shellSort()
    println(g.length)
    println(g.mkString(" "))
    println(cnt)
    retSeq.foreach(println)
  }

  implicit class RichSeqLong(seq: Seq[Long]) {
    def insertionSort(n: Int, g: Int)(idx: Int = g, cnt: Long = 0): (Seq[Long], Long) = {
      if (idx == n) {
        (seq, cnt)
      } else {
        val (nextSeq, thisCnt) = seq.swapEachG(g, seq(idx))(idx - g)
        nextSeq.insertionSort(n, g)(idx + 1, cnt + thisCnt)
      }
    }

    def swapEachG(g: Int, v: Long)(j: Int, cnt: Long = 0): (Seq[Long], Long) = {
      if (j < 0 || seq(j) <= v) (seq.updated(j + g, v), cnt)
      else seq.updated(j + g, seq(j)).swapEachG(g, v)(j - g, cnt + 1)
    }

    def recuresiveLoop(G:Seq[Int], cnt:Long): (Seq[Long], Long) = {
      G match {
        case Nil => (seq, cnt)
        case h +: tail => {
          val (nextSeq, thisCnt) = seq.insertionSort(seq.length, h)()
          nextSeq.recuresiveLoop(tail, cnt+thisCnt)
        }
      }
    }

    def shellSort(): (Seq[Long], Seq[Int], Long) = {
      val n = seq.length
      def genG(n : Long) = Stream.cons(n, Stream(3*n+1))
      val G: Seq[Int] = genG(1).takeWhile(_ < n).map(_.asInstanceOf[Int]).toList.reverse
      val (retSeq, cnt) = seq.recuresiveLoop(G, 0)
      (retSeq, G, cnt)
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt()
    val seq: Seq[Long] = {
      for (i <- 1 to n) yield {
        scala.io.StdIn.readLong()
      }
    }.toList
    val (retSeq, g, cnt) = seq.shellSort()
    println(g.length)
    println(g.mkString(" "))
    println(cnt)
    retSeq.foreach(println)
  }

  implicit class RichSeqLong(seq: Seq[Long]) {
    def insertionSort(n: Int, g: Int)(idx: Int = g, cnt: Long = 0): (Seq[Long], Long) = {
      if (idx == n) {
        (seq, cnt)
      } else {
        val (nextSeq, thisCnt) = seq.swapEachG(g, seq(idx))(idx - g)
        nextSeq.insertionSort(n, g)(idx + 1, cnt + thisCnt)
      }
    }

    def swapEachG(g: Int, v: Long)(j: Int, cnt: Long = 0): (Seq[Long], Long) = {
      if (j < 0 || seq(j) <= v) (seq.updated(j + g, v), cnt)
      else seq.updated(j + g, seq(j)).swapEachG(g, v)(j - g, cnt + 1)
    }

    def recuresiveLoop(G:Seq[Int], cnt:Long): (Seq[Long], Long) = {
      G match {
        case Nil => (seq, cnt)
        case h +: tail => {
          val (nextSeq, thisCnt) = seq.insertionSort(seq.length, h)()
          nextSeq.recuresiveLoop(tail, cnt+thisCnt)
        }
      }
    }

    def shellSort(): (Seq[Long], Seq[Int], Long) = {
      val n = seq.length
      def genG(n : Long) = Stream.cons(n, Stream(3*n+1))
      val G: Seq[Int] = genG(1).takeWhile(_ <= n).map(_.asInstanceOf[Int]).toList.reverse
      val (retSeq, cnt) = seq.recuresiveLoop(G, 0)
      (retSeq, G, cnt)
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt()
    val seq: Seq[Long] = {
      for (i <- 1 to n) yield {
        scala.io.StdIn.readLong()
      }
    }.toList
    val (retSeq, g, cnt) = seq.shellSort()
    println(g.length)
    println(g.mkString(" "))
    println(cnt)
    retSeq.foreach(println)
  }

  implicit class RichSeqLong(seq: Seq[Long]) {
    def insertionSort(n: Int, g: Int): (Seq[Long], Long) = {
      (g until n)
        .foldLeft((seq, 0l)) { (t, i) =>
          val (nextSeq, cnt) = t._1.swapEachG(i, g)
          (nextSeq, cnt + t._2)
        }
    }

    def swapEachG(i: Int, g: Int): (Seq[Long], Long) = {
      val v = seq(i)

      def jStream(j: Int): Stream[Int] = Stream.cons(j, jStream(j - g))

      val jSeq = jStream(i - g).takeWhile(idx => idx >= 0 && seq(idx) > v).toList
      if (jSeq.isEmpty) return (seq, 0)

      val (retSeq, cnt): (Seq[Long], Long) =
        jSeq.foldLeft((seq, 0l)) { (t, j) => (t._1.updated(j + g, t._1(j)), t._2 + 1) }

      (retSeq.updated(jSeq.last, v), cnt)
    }

    implicit class RichObj[T](obj: T) {
      def tap[U](f: T => U): T = {
        f(obj); obj;
      }
    }

    def recuresiveLoop(G: Seq[Int]): (Seq[Long], Long) = {
      G.foldLeft((seq, 0l)) { (t, g) =>
        val (nextSeq, cnt) = t._1.insertionSort(t._1.length, g)
        (nextSeq, t._2 + cnt)
      }
    }

    def shellSort(): (Seq[Long], Seq[Int], Long) = {
      val n = seq.length

      def genG(n: Long): Stream[Long] = Stream.cons(n, genG(3 * n + 1))

      val G: Seq[Int] = genG(1).takeWhile(_ <= n).map(_.asInstanceOf[Int]).toList.reverse
      val (retSeq, cnt) = seq.recuresiveLoop(G)
      (retSeq, G, cnt)
    }
  }

}


object Main {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt()
    val seq: Seq[Long] = {
      for (i <- 1 to n) yield {
        scala.io.StdIn.readLong()
      }
    }.toList
    val (retSeq, g, cnt) = seq.shellSort()
    println(g.length)
    println(g.mkString(" "))
    println(cnt)
    retSeq.foreach(println)
  }

  implicit class RichSeqLong(seq: Seq[Long]) {
    def insertionSort(n: Int, g: Int): (Seq[Long], Long) = {
      (g until n)
        .foldLeft((seq, 0l)) { (t, i) =>
          val (nextSeq, cnt) = t._1.swapEachG(i, g)
          (nextSeq, cnt + t._2)
        }
    }

    def swapEachG(i: Int, g: Int): (Seq[Long], Long) = {
      val v = seq(i)

      def jStream(j: Int): Stream[Int] = Stream.cons(j, jStream(j - g))

      val jSeq = jStream(i - g).takeWhile(idx => idx >= 0 && seq(idx) > v).toList
      if (jSeq.isEmpty) return (seq, 0)

      val (retSeq, cnt): (Seq[Long], Long) =
        jSeq.foldLeft((seq, 0l)) { (t, j) => (t._1.updated(j + g, t._1(j)), t._2 + 1) }

      (retSeq.updated(jSeq.last, v), cnt)
    }

    def recuresiveLoop(G: Seq[Int]): (Seq[Long], Long) = {
      G.foldLeft((seq, 0l)) { (t, g) =>
        val (nextSeq, cnt) = t._1.insertionSort(t._1.length, g)
        (nextSeq, t._2 + cnt)
      }
    }

    def shellSort(): (Seq[Long], Seq[Int], Long) = {
      val n = seq.length

      def genG(n: Long): Stream[Long] = Stream.cons(n, genG(3 * n + 1))

      val G: Seq[Int] = genG(1).takeWhile(_ <= n).map(_.asInstanceOf[Int]).toList.reverse
      val (retSeq, cnt) = seq.recuresiveLoop(G)
      (retSeq, G, cnt)
    }
  }

}


object Main {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt()
    val seq: Seq[Long] = {
      for (i <- 1 to n) yield {
        scala.io.StdIn.readLong()
      }
    }.toList
    val (retSeq, g, cnt) = seq.shellSort()
    println(g.length)
    println(g.mkString(" "))
    println(cnt)
    retSeq.foreach(println)
  }

  implicit class RichSeqLong(seq: Seq[Long]) {
    def insertionSort(n: Int, g: Int): (Seq[Long], Long) = {
      (g until n)
        .foldLeft((seq, 0l)) { (t, i) =>
          val (nextSeq, cnt) = t._1.swapEachG(i, g)
          (nextSeq, cnt + t._2)
        }
    }

    def swapEachG(i: Int, g: Int): (Seq[Long], Long) = {
      val v = seq(i)
      val jSeq = {for (j <- i to 0 by -g) yield j}.takeWhile(seq(_) > v)

      if (jSeq.isEmpty) return (seq, 0)

      val (retSeq, cnt): (Seq[Long], Long) =
        jSeq.foldLeft((seq, 0l)) { (t, j) => (t._1.updated(j + g, t._1(j)), t._2 + 1) }

      (retSeq.updated(jSeq.last, v), cnt)
    }

    def recuresiveLoop(G: Seq[Int], n:Int): (Seq[Long], Long) = {
      G.foldLeft((seq, 0l)) { (t, g) =>
        val (nextSeq, cnt) = t._1.insertionSort(n, g)
        (nextSeq, t._2 + cnt)
      }
    }

    def shellSort(): (Seq[Long], Seq[Int], Long) = {
      val n = seq.length

      def genG(n: Long): Stream[Long] = Stream.cons(n, genG(3 * n + 1))

      val G: Seq[Int] = genG(1)
        .takeWhile(_ <= n)
        .map(_.asInstanceOf[Int]).toList.reverse

      val (retSeq, cnt) = seq.recuresiveLoop(G, n)

      (retSeq, G, cnt)
    }
  }

}


import scala.collection.mutable
import scala.collection.mutable.ArraySeq

object Main {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt()
    val seq: ArraySeq[Long] = mutable.ArraySeq({for (i <- 1 to n) yield scala.io.StdIn.readLong()}: _*)
    val (retSeq, g, cnt) = seq.shellSort()

    println(g.length)
    println(g.mkString(" "))
    println(cnt)
    retSeq.foreach(println)
  }

  implicit class RichSeqLong(seq: ArraySeq[Long]) {
    def insertionSort(prevCnt: Long, n: Int, g: Int): (ArraySeq[Long], Long) = {
      (g until n).foldLeft((seq, prevCnt)) { (t, i) => t._1.swapEachG(t._2, i, g) }
    }

    def swapEachG(prevCnt: Long, i: Int, g: Int): (ArraySeq[Long], Long) = {

      val v = seq(i)
      val jSeq : Seq[Int]
      = {for (j <- i - g to 0 by -g) yield j}.takeWhile(j => seq(j) > v)

      for (j <- jSeq)  seq.update(j+g, seq(j))
      if (jSeq.nonEmpty) seq.update(jSeq.last, v)
      (seq, prevCnt + jSeq.length)
    }

    def recuresiveLoop(G: Seq[Int], n: Int): (ArraySeq[Long], Long) = {
      G.foldLeft((seq, 0l)) { (t, g) => t._1.insertionSort(t._2, n, g) }
    }

    def shellSort(): (ArraySeq[Long], Seq[Int], Long) = {
      val n = seq.length

      def genG(n: Long): Stream[Long] = Stream.cons(n, genG(3 * n + 1))

      val G: Seq[Int] = genG(1)
                        .takeWhile(_ <= n)
                        .map(_.asInstanceOf[Int])
                        .toList
                        .reverse

      val (retSeq, cnt) = seq.recuresiveLoop(G, n)

      (retSeq, G, cnt)
    }
  }
}


import scala.collection.immutable._
import scala.io.StdIn._
import scala.collection.mutable.Set
object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt
    var set = Set[String]()
    for(i <- 0 until n){
      var temp = readLine.split(" ")
      if(temp(0) == "insert") set.add(temp(1))
      else if(set.contains(temp(1))) println("yes");
      else  println("no");

    }

  }
}

Search III

Your task is to write a program of a simple dictionary which implements the following instructions:

insert str: insert a string str in to the dictionary

find str: if the distionary contains str, then print 'yes', otherwise print 'no'

Input

In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.

Output

Print yes or no for each find instruction in a line.

Constraints

A string consists of 'A', 'C', 'G', or 'T'

1 ≤ length of a string ≤ 12

n ≤ 1000000

Sample Input 1

5
insert A
insert T
insert C
find G
find A

Sample Output 1

no
yes

Sample Input 2

13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T

Sample Output 2

yes
no
no
yes
yes
yes

Notes

Template in C


import scala.io.StdIn.{readInt,readLine}
import scala.collection.mutable.HashMap

object Main extends App {
  val n = readInt
  val map = new HashMap[String,Int]
  for(i<-1 to n) {
    val s = readLine.split(" ")
    if(s(0)=="insert")
      map(s(1)) = 1
    else
      if(map.contains(s(1))) println("yes") else println("no")
  }

}


object Main extends App {
  val src = io.Source.stdin.getLines.toList.tail.map(_.split(" ").toList).map { case List(cmd, key) => (cmd, key) }

  def judge(tupLi: List[(String, String)], keyLi: List[String], asrLi: List[String]): List[String] = tupLi match {
    case h :: tail if h._1 == "find" =>
      if (keyLi.exists(_ == h._2)) judge(tail, keyLi, "yes" :: asrLi)
      else judge(tail, keyLi, "no" :: asrLi)
    case h :: tail if h._1 == "insert" =>
      judge(tail, h._2 :: keyLi, asrLi)
    case Nil => asrLi.reverse
  }

  println(judge(src, Nil, Nil).mkString("\n"))
}


import scala.io.StdIn.{readInt,readLine}

object Main extends App {
  type Set = String => Boolean

  def contains(s:Set, elem:String):Boolean = s(elem)
  def singletonSet(elem:String):Set = x => x==elem
  def union(s:Set, t:Set):Set = x => contains(s,x) || contains(t,x)

  val n = readInt

  def loop(i:Int, s:Set, str:String):String =
    if(i>n) str.dropRight(1)
    else {
      val l = readLine.split(" ")
      if(l(0)(0)=='i') loop(i+1, union(singletonSet(l(1)),s),str)
      else if(contains(s,l(1))) loop(i+1, s, str+"yes\n")
      else loop(i+1, s, str+"no\n")
    }
  val l = readLine.split(" ")
  println(loop(2, singletonSet(l(1)),""))
}


import scala.io.StdIn.{readInt,readLine}
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  type Set = String => Boolean

  def contains(s:Set, elem:String):Boolean = s(elem)
  def singletonSet(elem:String):Set = x => x==elem
  def union(s:Set, t:Set):Set = x => contains(s,x) || contains(t,x)

  val n = readInt

  def loop(i:Int, s:Set, a:ArrayBuffer[String]):ArrayBuffer[String] =
    if(i>n) a
    else {
      val l = readLine.split(" ")
      val isInsert = l(0)(0) == 'i'
      val newSet = if(isInsert) union(singletonSet(l(1)),s) else s
      if(!isInsert && contains(s,l(1))) a += "yes"
      else if(!isInsert && !contains(s,l(1))) a+="no"
      loop(i+1, newSet, a)
    }
  println(loop(1, singletonSet("-"),new ArrayBuffer[String]()).mkString("\n"))
}


import scala.io.StdIn.{readInt, readLine}
import scala.reflect.ClassTag
case class Node[A](data: A, var next: Option[Node[A]])
class Dictionary[A](val size: Int)(implicit m: ClassTag[Option[Node[A]]]) {
    val dict: Array[Option[Node[A]]] = m.newArray(size).map(a => None)

    def insert(target: A): Unit = {
        val index = target.hashCode % size
        def insert1(node: Option[Node[A]]): Unit = node match {
            case None => dict(index) = Option(new Node[A](target, None))
            case Some(a) => a.next match {
                case None => a.next = Option(new Node[A](target, None))
                case Some(b) if b.data != target => insert1(a.next)
            }
        }
        insert1(dict(index))
    }
    def find(target: A): Boolean = {
        val index = target.hashCode % size
        def find1(node: Option[Node[A]]): Boolean = node match {
            case None => false
            case Some(a) => if (a.data == target) true else find1(a.next)
        }
        find1(dict(index))
    }

}
object Dictionary {
    def apply[A](size: Int): Dictionary[A] = new Dictionary(size)
}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val dict = Dictionary[String](len)
        for (i <- (1 to len)) {
            readLine.split(" ") match {
                case Array("insert", v) => dict.insert(v)
                case Array("find", v) => dict.find(v) match {
                    case true => println("yes")
                    case false => println("no")
                }
            }
        }
    }
}


import scala.io.StdIn.{readInt, readLine}
import scala.reflect.ClassTag
case class Node[A](data: A, var next: Option[Node[A]])
class Dictionary[A](val size: Int)(implicit m: ClassTag[Option[Node[A]]]) {
    val dict: Array[Option[Node[A]]] = m.newArray(size).map(a => None)

    def insert(target: A): Unit = {
        val index = target.hashCode % size
        def go(node: Option[Node[A]]): Unit = node match {
            case None => dict(index) = Option(new Node[A](target, None))
            case Some(a) if a.data != target => a.next match {
                case None => a.next = Option(new Node[A](target, None))
                case _ => go(a.next)
            }
            case _ => ()
        }
        go(dict(index))
    }
    def find(target: A): Boolean = {
        val index = target.hashCode % size
        def go(node: Option[Node[A]]): Boolean = node match {
            case None => false
            case Some(a) => if (a.data == target) true else go(a.next)
        }
        go(dict(index))
    }
    override def toString(): String = {
        def nodeToString(node: Option[Node[A]]): String = node match {
            case None => "None"
            case Some(a) => a.data + " -> " + nodeToString(a.next)
        }
        val sb = new StringBuilder()
        (0 until dict.length).foldLeft(sb) {(builder, idx) =>
            builder.append(idx + " : ")
            dict(idx) match {
                case None => builder.append("None")
                case node => builder.append(nodeToString(node))
            }
            builder.append("\n")
        }
        sb.toString
    }

}
object Dictionary {
    def apply[A](size: Int): Dictionary[A] = new Dictionary(size)
}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val dict = Dictionary[String](len)
        val l = (1 to len).foldLeft(Nil: List[String]) { (list, dummy) =>
            readLine.split(" ") match {
                case Array("insert", v) => dict.insert(v); list
                case Array("find", v) => dict.find(v) match {
                    case true => "yes" :: list
                    case false => "no" :: list
                }
            }
        }
        println(l.reverse.mkString("\n"))
    }
}


import scala.collection.mutable

object Main extends App {

  val sc = new java.util.Scanner(Console.in)

  def next() = sc.next()
  def nextInt() = next().toInt

  val n = nextInt()
  val input = Seq.fill(n)((next(), next()))

  var dict = mutable.Set[String]()

  for ((cmd, str) <- input) {
    cmd match {
      case "insert" => dict add str
      case "find"   => println(if (dict contains str) "yes" else "no")
    }
  }
}


import scala.io.StdIn

object Main extends App {

  val max = 84*12 // T * 12 char: 1008
  val min = 65*12 // A * 12 char:  780
  //
  // 16,777,216

  val m = max
  val arrayMax = 1000000

  def ctoi(data: String) = data.foldLeft(0)((acc, e) => acc+e)

  // A: 65, C:67, G:71, T:84
  def makeHash1(key: Int) = {
    key % m
  }

  def makeHash2(key: Int) = {
    1 + key % (m - 1)
  }

  def makeHash(key: Int, i: Int) = {
    (makeHash1(key) + i * makeHash2(key)) % m
  }

  val n = StdIn.readLine().trim.toInt

  val dict = Array.fill(arrayMax)("")

  def insert(data: String): Unit = {
    var i = 0
    val key = ctoi(data)
    var colision = true
    while(colision){
      val j = makeHash(key, i)
      if(dict(j) == "") {
        dict(j) = data
        colision = false
      }
      else i = i + 1
    }
  }

  def search(data: String): Int = {
    val key = ctoi(data)
    var i = key
    var ret = -1
    while(ret < 0 && i < arrayMax){
      if(dict(i) == data) {
        ret = i
      }
      i += 1
    }
    ret
  }

  val result = (0 until n).map{ _ =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      insert(cmd(1))
      ""
    } else {
      if(search(cmd(1)) >= 0) f"yes%n" else f"no%n"
    }
  }.filterNot( p => p == "")

  print(result.mkString(""))

}


import scala.io.StdIn
object Main extends App {

  val m = 1046527
  val arrayMax = 1000000

  //def ctoi(data: String) = data.foldLeft(0)((acc, e) => acc+e)
  def ctoi(data: String) = data.zipWithIndex.foldLeft(0){ (acc, e) =>
    acc + e._2 * (if(e._1 == 'A') 1 else if(e._1 == 'C') 2 else if(e._1 == 'G') 3 else 4)
  }

  // A: 65, C:67, G:71, T:84
  def makeHash1(key: Int) = {
    key % m
  }

  def makeHash2(key: Int) = {
    1 + key % (m - 1)
  }

  //def makeHash(key: Int, i: Int) = (makeHash1(key) + i * makeHash2(key)) % m
  def makeHash(key: Int, i: Int) = makeHash1(key) + i

  val n = StdIn.readLine().trim.toInt

  val dict = Array.fill(arrayMax + 10)("")

  def insert(data: String): Unit = {
    var i = 0
    val key = ctoi(data)
    var colision = true
    while(colision){
      val j = makeHash(key, i)
      if(dict(j) == "") {
        dict(j) = data
        colision = false
      } else if(dict(j) == data){
        colision = false
      }
      else {
        i = i + 1
      }
    }
  }

  def search(data: String): Int = {
    val key = ctoi(data)
    var i = key
    var ret = -1
    while(ret < 0 && i < arrayMax){
      if(dict(i) == data) {
        ret = i
      }
      i += 1
    }
    ret
  }

  (0 until n).foreach{ _ =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      insert(cmd(1))
    } else {
      if(search(cmd(1)) >= 0) {
        println("yes")
      } else {
        println("no")
      }
    }
  }

}


import scala.io.StdIn
object Main extends App {

  val m = 1046527
  val arrayMax = 1000000

  //def ctoi(data: String) = data.foldLeft(0)((acc, e) => acc+e)
  def ctoi(data: String) = data.zipWithIndex.foldLeft(0){ (acc, e) =>
    acc + e._2 * (if(e._1 == 'A') 1 else if(e._1 == 'C') 2 else if(e._1 == 'G') 3 else 4)
  }

  // A: 65, C:67, G:71, T:84
  def makeHash1(key: Int) = {
    key % m
  }

  def makeHash2(key: Int) = {
    1 + key % (m - 1)
  }

  //def makeHash(key: Int, i: Int) = (makeHash1(key) + i * makeHash2(key)) % m
  //def makeHash(key: Int, i: Int) = makeHash1(key) + i

  val n = StdIn.readLine().trim.toInt

  val dict = Array.fill(arrayMax + 10)("")

  def insert(data: String): Unit = {
    var i = 0
    //val key = ctoi(data)
    var colision = true
    while(colision){
      //val j = makeHash(key, i)
      val j = (data.hashCode.abs + i) % arrayMax
      if(dict(j) == "") {
        dict(j) = data
        colision = false
      } else if(dict(j) == data){
        colision = false
      }
      else {
        i = i + 1
      }
    }
  }

  def search(data: String): Int = {
    //val key = ctoi(data)
    var i = (data.hashCode.abs) % arrayMax
    var ret = -1
    while(ret < 0 && i < arrayMax){
      if(dict(i) == data) {
        ret = i
      }
      i += 1
    }
    ret
  }

  val result = (0 until n).foldLeft(List.empty[String]){ (acc, _) =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      insert(cmd(1))
      acc
    } else {
      if(search(cmd(1)) >= 0) {
        "yes"::acc
      } else {
        "no"::acc
      }
    }
  }
  println(result.reverse.mkString(f"%n"))

}


import scala.collection.mutable.ListBuffer
import scala.io.StdIn
object Main extends App {

  val n = StdIn.readLine().trim.toInt

  val result = (0 until n).foldLeft(ListBuffer.empty[String], Set.empty[String]){
    case ((acc, dict), _) =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      (acc, dict + cmd(1))
    } else {
      if(dict.contains(cmd(1))) {
        (acc += "yes", dict)
      } else {
        (acc += "no", dict)
      }
    }
  }
  println(result._1.mkString(f"%n"))

}


import scala.collection.mutable.{ListBuffer, TreeSet}
import scala.io.StdIn
object Main extends App {

  val n = StdIn.readLine().trim.toInt

  val result = (0 until n).foldLeft(ListBuffer.empty[String], TreeSet.empty[String]){
    case ((acc, dict), _) =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      (acc, dict + cmd(1))
    } else {
      if(dict.contains(cmd(1))) {
        (acc += "yes", dict)
      } else {
        (acc += "no", dict)
      }
    }
  }
  println(result._1.mkString(f"%n"))

}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
object Main extends App {

  val n = StdIn.readLine().trim.toInt

  // RuntimeError !! (Hash値が悪さしている？)
  //val result = (0 until n).foldLeft(ListBuffer.empty[String], HashSet.empty[String]){
  val result = (0 until n).foldLeft(ArrayBuffer.empty[String], Set.empty[String]){
      case ((acc, dict), _) =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      (acc, dict + cmd(1))
    } else {
      if(dict.contains(cmd(1))) {
        (acc += "yes", dict)
      } else {
        (acc += "no", dict)
      }
    }
  }
  println(result._1.mkString(f"%n"))

}


import scala.io.StdIn
object Main extends App {
  val n = StdIn.readLine().trim.toInt
  val result = (0 until n).foldLeft(List.empty[String], Set.empty[String]){
      case ((acc, dict), _) =>
    val cmd = StdIn.readLine().split(' ')
    if(cmd(0) == "insert"){
      (acc, dict + cmd(1))
    } else {
      if(dict.contains(cmd(1))) {
        ("yes" :: acc, dict)
      } else {
        ("no" :: acc, dict)
      }
    }
  }

  println(result._1.reverse.mkString(f"%n"))

}


import scala.io.StdIn.{readInt, readLine}

object Main extends App {

  val n = readInt()
  val in = readLine().split(' ').map(_.toInt)
  val a = Array.fill(n)(0)
  val b = Array.fill(n + 1)(0L)
  val mod = 1000000007

  for (i <- 0 until n) {
    a(i) = in(i)
    b(i + 1) = b(i) + a(i)
  }

  var ans = 0L

  for (i <- 0 until n) {
    val sum = b(n) - b(i + 1) % mod

    ans += a(i) * sum
    ans %= mod
  }
  println(ans)
}

Score : 300 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

Constraints

2 \leq N \leq 2\times 10^5

0 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} A_i A_j, modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

11

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

Sample Input 2

4
141421356 17320508 22360679 244949

Sample Output 2

437235829


import scala.io.StdIn.{readInt, readLine}
import scala.collection.mutable.ListBuffer

object Main extends App {

  val n = readInt()
  val in = readLine().split(' ').map(_.toInt)
  val a = ListBuffer.fill(n)(0)
  val b = ListBuffer.fill(n + 1)(0L)
  val mod = 1000000007

  for (i <- 0 until n) {
    a(i) += in(i)
    b(i + 1) += b(i) + a(i)
  }

  var ans = 0L

  for (i <- 0 until n) {
    val sum = b(n) - b(i + 1) % mod

    ans += a(i) * sum
    ans %= mod
  }
  println(ans)
}


import scala.io.StdIn.{readInt, readLine}
import scala.collection.mutable.ListBuffer

object Main extends App {

  val n = readInt()
  val a = readLine().split(' ').map(_.toInt)
  val b = ListBuffer.fill(n + 1)(0L)
  val mod = 1000000007

  for (i <- 0 until n) b(i + 1) += b(i) + a(i)

  var ans = 0L

  for (i <- 0 until n) {
    val sum = b(n) - b(i + 1) % mod

    ans += a(i) * sum
    ans %= mod
  }
  println(ans)
}


import scala.io.StdIn.{readInt, readLine}

object Main extends App {

  val n = readInt()
  val a = readLine().split(' ').map(_.toLong)

  var sum: Long = 0

  for (i <- 0 until n - 1)
    for (j <- i + 1 until n)
      sum += (a(i) * a(j))

  println(sum % (math.pow(10, 9) + 7).toLong)
}


object Main extends App {
  val N = io.StdIn.readLine.toInt

  val param = io.StdIn.readLine.split(" ").map(_.toLong)

  val ret = (0 to param.length - 1).foldLeft(0l) { (acc, v) =>
    val ret = (v + 1 to param.length - 1).foldLeft(0l) { (acc2, w) =>
      (acc2 + ((param(v) * param(w)) % (1000000000 + 7))) % (1000000000 + 7)
    }
    (ret + acc) % (1000000000 + 7)
  }

  println(ret)

}


object Main extends App {
  val mod = 1000000007
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val a = Array.fill(n)(sc.nextLong())
  val cumSum = a.scanLeft(0L)((x, y) => x + y).tail
  val ans = for(i <- 0 until n) yield {
    a(i) * (cumSum(cumSum.length-1) - cumSum(i)) % mod
  }
  println(ans.sum % mod)
}


import scala.io.StdIn._
import scala.math._
import scala.util.control.Breaks

object Main extends App with StdInHelper {
  val n = readInt
  val as = readLongs

  var result = 0L
  as.combinations(2)
    .map { case Array(a, b) => (a * b) % 1000000007L }
    .foreach(a => result = (result + a) % 1000000007L)

  println(result)
}

trait StdInHelper {
  def readStrings = {
    val l = readLine
    if (l == "") Array.empty[String]
    else l.split(" ")
  }
  def readInts = readStrings.map(_.toInt)
  def readLongs = readStrings.map(_.toLong)
  def readDoubles = readStrings.map(_.toDouble)
  def readBigInts = readStrings.map(BigInt.apply(_))
  def readBigDecimals = readStrings.map(BigDecimal.apply(_))
}


import scala.io.StdIn._

object Main extends App {

  val n = readInt()
  val A = readLine().split(" ").map(_.toLong)
  def solve() = {
    val mod = (1e9+7).toInt
    (0 until n-1).foldLeft(0L) { (acc, i) =>
      val sum = (i+1 until n).foldLeft(0L) { (accIn, j) =>
        (accIn + A(i) * A(j)) % mod
      }
      (acc + sum) % mod
    } % mod
  }

  println(solve())

}


import scala.io.StdIn

object Main extends App {
  StdIn.readLine()
  val nums = StdIn.readLine().split(' ').map(BigInt(_))

  val sum = nums.sum

  val tmp1 = sum*sum - nums.map(n=>n*n).sum

  val ans = (tmp1/2) % (BigInt((math.pow(10L,9L)+7).toLong))

  println(ans)
}


import scala.io.StdIn

object Main extends App {
  StdIn.readLine()
  val nums = StdIn.readLine().split(' ').map(_.toLong)

  val sum = nums.sum

  val tmp1 = sum*sum - nums.map(n=>n*n).sum

  val ans = (tmp1/2)%(math.pow(10L,9L)+7).toLong

  println(ans)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val a = Array.fill(n)(sc.nextLong())

  val mod = 1000000007

  def plus(a: Long, b: Long): Long = (a + b) % mod
  var ans = 0L
  for {
    i <- 0 until n
    j <- i+1 until n
  } {
    ans = plus(ans, a(i) * a(j))
  }

  println(ans)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val as = List.fill(n)(sc.nextLong())
  val m = 1000000

  def divisors(n: Int): Array[Int] = {
    val divisors = Array.fill(n+1)(0)
    for (i <- 2 to n if divisors(i) == 0) {
      var k = 1
      while (i * k <= n) {
        if (divisors(i * k) == 0) {
          divisors(i * k) = i
        }
        k += 1
      }
    }
    divisors
  }

  val divisor = divisors(m)

  def primeFactors(n: Int, res: IndexedSeq[Int] = IndexedSeq()): IndexedSeq[Int] = {
    if (n == 1) {
      res
    } else {
      val d = divisor(n)
      if (d == n) {
        res :+ n
      } else {
        var m = n
        var res2 = res
        while (m % d == 0) {
          m /= d
          res2 :+= d
        }
        primeFactors(m, res2)
      }
    }
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a else gcd(b, a % b)
  }

  val exist = Array.fill(m+1)(false)
  var pair = true
  as.map(a => primeFactors(a.toInt)).foreach(fs =>
    for (f <- fs.distinct) {
      if (exist(f)) {
        pair = false
      } else {
        exist(f) = true
      }
    }
  )

  if (pair) {
    println("pairwise coprime")
  } else if (as.reduceLeft[Long]{case (x, y) => gcd(x, y)} == 1) {
    println("setwise coprime")
  } else {
    println("not coprime")
  }
}

Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.


import java.io.{BufferedOutputStream, BufferedReader, FileOutputStream, InputStreamReader, PrintWriter}
import java.lang

import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  val DEBUG = false

  lazy val debugOut: PrintWriter = {
    new PrintWriter(new BufferedOutputStream(new FileOutputStream("log.txt", true)))
  }

  def log(message: => String): Unit = {
    if (DEBUG) {
      debugOut.println(message)
    }
  }

  def debug(closure: => Unit): Unit = {
    if (DEBUG) {
      closure
    }
  }

  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        if (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

  @tailrec
  def gcd(a: Int, b: Int): Int = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

  def lcm(a: Long, b: Long): Long = {
    a / gcd(a, b) * b
  }

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]
    val as = getArray[Int]

    val primeMap = Array.ofDim[Int](1000001)

    var max = 0
    for (a <- as) {
      for (p: Int <- primes(a)) {
        val count = primeMap(p) + 1
        primeMap(p) = count
        max = Math.max(max, count)
      }
    }

    out.println(
      if (max == 1) {
        "pairwise coprime"
      } else if (max == n) {
        "not coprime"
      } else {
        "setwise coprime"
      }
    )

    out.flush()
  }
}


import java.io.{BufferedOutputStream, BufferedReader, FileOutputStream, InputStreamReader, PrintWriter}
import java.lang

import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  val DEBUG = false

  lazy val debugOut: PrintWriter = {
    new PrintWriter(new BufferedOutputStream(new FileOutputStream("log.txt", true)))
  }

  def log(message: => String): Unit = {
    if (DEBUG) {
      debugOut.println(message)
    }
  }

  def debug(closure: => Unit): Unit = {
    if (DEBUG) {
      closure
    }
  }

  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

  @tailrec
  def gcd(a: Int, b: Int): Int = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

  def lcm(a: Long, b: Long): Long = {
    a / gcd(a, b) * b
  }

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]
    val as = getArray[Int]

    log("=== start")

    val primeMap = mutable.HashMap.empty[Int, Int]

    for (a <- as) {
      for (p <- primes(a).map(_.toInt).toSet) {
        primeMap(p) = primeMap.getOrElse(p, 0) + 1
      }
    }

    var max = 0
    for ((_, count) <- primeMap) {
      max = Math.max(max, count)
    }

    out.println(
      if (max == 1) {
        "pairwise coprime"
      } else if (max == n) {
        "not coprime"
      } else {
        "setwise coprime"
      }
    )

    out.flush()
    log("=== end")
    debug {
      debugOut.flush()
    }
  }
}


import scala.io.StdIn._
object Main extends App {
  val in = new java.util.Scanner(System.in)
  val H, W, M = in.nextInt
  val rows = new Array[Int](H + 1)
  val cols = new Array[Int](W + 1)

  val ts = Array.fill(M){
    val y = in.nextInt
    val x = in.nextInt
    rows(y) += 1
    cols(x) += 1
    (x, y)
  }

  val rMax = rows.max
  val tRows = rows.count(_ == rMax)
  val cMax = cols.max
  val tCols = cols.count(_ == cMax)
  val targetBomb = ts.count(t => rows(t._2) == rMax && cols(t._1) == cMax) == tRows * tCols
  println(rMax + cMax - (if (targetBomb) 1 else 0))
}

Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

5 5 10
2 5
4 3
2 3
5 5
2 2
5 4
5 3
5 1
3 5
1 4

Sample Output 3

6


import scala.io.StdIn._
object Main extends App {
  val in = new java.util.Scanner(System.in)
  val H, W, M = in.nextInt
  val ts = Array.fill(M)((in.nextInt, in.nextInt))
  def filter(map: Map[Int, Array[Int]]): (Int, Map[Int, Array[Int]]) = {
    val max = map.values.map(_.size).max
    (max, map.filter{case (k, v) => v.size == max})
  }

  val (rMax, rows) = filter(ts.groupMap(_._1)(_._2))
  val (cMax, cols) = filter(ts.groupMap(_._2)(_._1))
  val colKeys = cols.keySet.toArray

  val noCross = rows.values.exists {cs => cs.diff(colKeys).isEmpty}

  println(rMax + cMax - (if (noCross) 0 else 1))
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datH,datW,datM) = readLine.split(" ").map(_.toInt)
    val datS = for (i <- 1 to datM) yield {
      val Array(datY,datX) = readLine.split(" ").map(_.toInt)
      (datY - 1, datX - 1)
    }

    // initialize
    var aryH = new Array[Int](datH)
    // for (i <- 0 until aryH.length) aryH(i) = 0 // default 0
    var aryW = new Array[Int](datW)
    // for (i <- 0 until aryW.length) aryW(i) = 0 // default 0

    // counting
    datS.map{a => aryH(a._1) += 1; aryW(a._2) += 1}
    val maxH = aryH.max
    val maxW = aryW.max

    // [[crossing check]]
    // get candidate row/col idx
    val candH = aryH.zipWithIndex.filter(a => a._1 == maxH).map(a => a._2)
    val candW = aryW.zipWithIndex.filter(a => a._1 == maxW).map(a => a._2)

    // init matrix
    var aryM = Array.ofDim[Int](datH, datW)
    // for(i <- 0 until datH; j <- 0 until datW) aryM(i)(j) = 0 //default 0
    // make matrix
    datS.map{a => aryM(a._1)(a._2) = 1}

    // cross check
    val valCross = candH.map{y =>
      candW.map{x =>
        aryM(y)(x)
      }
    }.flatten.min

    val ans = maxH + maxW - valCross
    println(ans)
  }
}


object Main extends App {
  val sc = new FastScanner(System.in)
  val h, w, m = sc.nextInt()
  val hw = Array.fill(m)((sc.nextInt()-1, sc.nextInt()-1))
  var bombs = hw.map{case (i, j) => i * w + j}.sorted
  val hb = Array.fill(h)(0)
  val wb = Array.fill(w)(0)
  for ((h, w) <- hw) {
    hb(h) += 1
    wb(w) += 1
  }

  def binSearch(begin: Int, end: Int, k: Int): Int = {
    if (end - begin <= 1) {
      begin
    } else {
      val m = begin + (end - begin) / 2
      if (bombs(m) >= k) binSearch(m, end, k) else binSearch(begin, m, k)
    }
  }

  val hMax = hb.max
  val wMax = wb.max
  val hMaxIndices = hb.zipWithIndex.collect{case (b, idx) if b == hMax => idx}
  val wMaxIndices = wb.zipWithIndex.collect{case (b, idx) if b == wMax => idx}
  if (hMaxIndices.length * wMaxIndices.length > m) {
  } else {
    var found = false
    for {
      hi <- hMaxIndices
      wi <- wMaxIndices
      if !found
    } {
      if (binSearch(0, m, hi * w + wi) == hi * w + wi) {
        found = true
      }
    }
    println(if (found) hb.max + wb.max else hb.max + wb.max - 1)
  }
}

class FastScanner(source: java.io.InputStream) {
  val buf = new Array[Byte](1024)
  var now, end = 0

  def isPrintable(b: Byte): Boolean = 33 <= b && b <= 126
  def isNum(b: Byte): Boolean = 48 <= b && b <= 57

  def hasNextByte: Boolean = {
    if (now < end) {
      true
    } else {
      now = 0
      end = source.read(buf)
      end > 0
    }
  }

  def nextByte(): Byte = {
    if (hasNextByte) {
      val b = buf(now)
      now += 1
      b
    } else {
      -1
    }
  }

  def hasNext: Boolean = {
    while (hasNextByte && !isPrintable(buf(now))) {
      now += 1
    }
    hasNextByte
  }

  def next(): String = {
    if (hasNext) {
      val sb = new StringBuilder()
      var b = nextByte()
      while (isPrintable(b)) {
        sb += b.toChar
        b = nextByte()
      }
      sb.toString
    } else {
      throw new NoSuchElementException()
    }
  }

  def nextInt(): Int = {
    nextLong().toInt
  }

  def nextLong(): Long = {
    if (hasNext) {
      var b = nextByte()
      var sign = 1
      var n = 0L
      if (b == '-') {
        sign = -1
        b = nextByte()
      }
      while (isNum(b)) {
        n = n * 10 + (b - 48)
        b = nextByte()
      }
      sign * n
    } else {
      throw new NoSuchElementException()
    }
  }

  def nextDouble(): Double = next().toDouble
}


object Main extends App{
  val n = io.StdIn.readInt()
  val fixed_n = n % 1000
  if(fixed_n == 0){
    println(0)
  }else {
    println(1000 - fixed_n)
  }
}

Score : 100 points

Problem Statement

We will buy a product for N yen (the currency of Japan) at a shop.

If we use only 1000-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

1 \leq N \leq 10000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.


object Main extends App {
  //  val file = new File("targetfile")
  val testdata =
    """
1200"""
// 出力例1
// 3
//   val sc = new java.util.Scanner(testdata)
 val sc = new java.util.Scanner(System.in)

  val _x = sc.nextInt

  if (_x % 1000 > 0) {
    println(1000 - _x % 1000)
  } else {
    println(0)
  }
}


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val num = sc.nextInt()
    val result = (10000 - num) % 1000
    println(result)
  }
}


import io.StdIn._

object Main extends App {
  val num = readInt
  println((1000 - (num % 1000)) % 1000)
}


import io.StdIn._

object Main extends App {
  val num = readInt
  println(1000 - (num % 1000))
}


import scala.math.floor

object Main extends App {

  def change(input: Int) = {
    var firstInt = 0
    if(input % 1000 == 0) {
      firstInt = floor(input / 1000).toInt
    } else {
      firstInt = floor(input / 1000).toInt + 1
    }

    val money = firstInt * 1000
    println(money - input)
  }
}


import io.StdIn.{readInt, readLine}
object Main extends App {
  val n = readInt

  var money = 0
  while (money < n) money += 1000
  var result = money-n
  println(result)
}


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val n = inputs.head.toInt

  println(solve(n))

  def solve(n: Int): Int = {
    n % 1000 match {
      case 0 => 0
      case v => 1000 - v
    }
  }
}


import scala.math

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  def divisors(n: Int): List[Int] =
    for (i <- (1 to n).toList if n % i == 0) yield i
  var n = sc.nextInt() % 1000
  if (n == 0){
    println(0)
    sys.exit()
  }
  println(1000 - n)
}


import java.util.Scanner

import scala.io.StdIn._

object Main extends App {

  val n = readInt()

  def solve() = {
    (10000 - n) % 1000
  }

  println(solve())

}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

  @tailrec
  def gcd(a: Int, b: Int): Int = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

  def lcm(a: Long, b: Long): Long = {
    a / gcd(a, b) * b
  }

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))

    out.println((1000 - get[Int] % 1000) % 1000)
    out.flush()
  }
}


import java.util.Scanner

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

  val z = 1000 - N % 1000
  println(if (z == 1000) 0 else z)
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set, TreeSet}
import scala.util.Random
import java.util.Date

object Main extends App {
  val startTime = new Date().getTime // to milli seconds

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val D = in.next().toInt
  val c = new Array[Long](26+1)
  val s = Array.ofDim[Long](D+1, 26+1)

  for (i <- 1 to 26) {
    c(i) = in.next().toInt
  }
  for (d <- 1 to D) {
    for (i <- 1 to 26) {
      s(d)(i) = in.next().toInt
    }
  }

  //
  class Board(val t: Array[Int]) {

    // 各コンテストの開催日をセットで保持する
    private val eventDays = Array.fill(26+1)(TreeSet[Int]())

    var score: Long = {
      var res = 0L

      val last = new Array[Int](26+1)
      for (day <- 1 to D) {
        val now = t(day)

        last(now) = day
        eventDays(now) += day

        res += s(day)(now)
        for (contest <- 1 to 26) {
          res -= c(contest) * (day - last(contest))
        }
      }

      res
    }

    // ${day}日の開催コンテストを, ${contest}に変更する
    def update(day: Int, contest: Int): Unit = {
      def tousa(l: Int): Int = ((1 + l) * l) / 2

      score -= s(day)(t(day))
      score += s(day)(contest)

      val delSet = eventDays(t(day))
      delSet -= day
      var start = delSet.maxBefore(day).getOrElse(0)
      var end = delSet.minAfter(day).map(_ - 1).getOrElse(D)
      score += c(t(day)) * tousa((day-1) - start)
      score += c(t(day)) * tousa(end - day)
      score -= c(t(day)) * tousa(end - start)

      val addSet = eventDays(contest)
      start = addSet.maxBefore(day).getOrElse(0)
      end = addSet.minAfter(day).map(_ - 1).getOrElse(D)
      score -= c(contest) * tousa((day-1) - start)
      score -= c(contest) * tousa(end - day)
      score += c(contest) * tousa(end - start)
      addSet += day

      t(day) = contest
    }
  }

  /** functions **/

  /** solve **/
  val t = new Array[Int](D+1)
  val last = new Array[Int](26+1)
  for (d <- 1 to D) {
    val (_, ty) =
      s(d).zipWithIndex
        .drop(1)
        .map{ case (s, ty) => (s + c(ty) * (d - last(ty)), ty) }
        .max

    t(d) = ty
    last(ty) = d
  }

  val board = new Board(t)

  val endTime = 1400
  var currentScore = board.score
  var bestAns = t.clone
  var bestScore =  currentScore

  val annStartTime = new Date().getTime
  var currentTime = annStartTime

  val T = endTime - annStartTime // 焼きなましにかける時間
  val R = 10000

  while ((new Date().getTime - startTime) < endTime) {
    for (_ <- 1 to 1000) {
      val time = currentTime - annStartTime // 焼きなまし法開始からの時間

      /** 変更 **/
      {
        val d = Random.nextInt(D) + 1
        val ty = Random.nextInt(26) + 1

        val tmp = board.t(d)
        board.update(d, ty)

        val nextScore = board.score // 遷移後のスコアを計算

        // スコアが悪くなったときでも、次の状態に移動する遷移する場合はtrue。
        val ForceNext = T * Random.nextInt(R) < (T-time) * R // １次関数

        if (nextScore > currentScore || ForceNext)
          currentScore = nextScore // 遷移を適用
        else
          board.update(d, tmp) // 遷移を破棄

        // ベストスコアを保存
        if (currentScore > bestScore) {
          bestScore = currentScore
          bestAns = board.t.clone // 現在の盤面を渡す
        }
      }

      /** swap **/
      {
        val d = Random.nextInt(D-1) + 1

        val tmp = board.t(d)
        board.update(d, board.t(d+1))
        board.update(d+1, tmp)

        val nextScore = board.score // 遷移後のスコアを計算

        // スコアが悪くなったときでも、次の状態に移動する遷移する場合はtrue。
        val ForceNext = T * Random.nextInt(R) < (T-time) * R // １次関数

        if (nextScore > currentScore || ForceNext)
          currentScore = nextScore // 遷移を適用
        else {
          val tmp2 = board.t(d)
          board.update(d, board.t(d+1))
          board.update(d+1, tmp2)
        }

        // ベストスコアを保存
        if (currentScore > bestScore) {
          bestScore = currentScore
          bestAns = board.t.clone // 現在の盤面を渡す
        }
      }
    }
  }

  val last2 = new Array[Int](26+1)
  for (d <- 1 to D) {
    if (d == D) {
      val (_, ty) =
        s(d).zipWithIndex
          .drop(1)
          .map{ case (s, ty) => (s + c(ty) * (d - last2(ty)), ty) }
          .max

      board.t(d) = ty
    }
    else {
      last2(board.t(d)) = d
    }
  }

  for (d <- 1 to D) {
    pw.println(board.t(d))
  }
  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

Problem Statement

AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to schedule contests for D days so that user satisfaction is as high as possible. For every day, AtCoder will hold exactly one contest, and each contest will end on that day. The satisfaction is calculated as follows.

The satisfaction at the beginning of day 1 is 0. Satisfaction can be negative.

Holding contests increases satisfaction. The amount of increase will vary depending on a variety of factors. Specifically, we know in advance that holding a contest of type i on day d will increase the satisfaction by s_{d,i}.

If a particular type of contest is not held for a while, the satisfaction decreases. Each contest type i has an integer c_i, and at the end of each day d=1,2,...,D, the satisfaction decreases as follows. Let \mathrm{last}(d,i) be the last day before day d (including d) on which a contest of type i was held. If contests of type i have never been held yet, we define \mathrm{last}(d,i)=0. At the end of day d, the satisfaction decreases by \sum _{i=1}^{26}c_i \times (d-\mathrm{last}(d,i)).

Please schedule contests on behalf of AtCoder.
If the satisfaction at the end of day D is S, you will get a score of \max(10^6 + S, 0).
There are 50 test cases, and the score of a submission is the total scores for each test case.
You can make submissions multiple times, and the highest score among your submissions will be your score.

Constraints

D = 365

Each c_i is an integer satisfying 0\leq c_i \leq 100.

Each s_{d,i} is an integer satisfying 0\leq s_{d,i} \leq 20000.

Input

Input is given from Standard Input in the following format:

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}

Output

Let t_d (1\leq t_d \leq 26) be the type of the contest that will be held at day d.
Print D integers t_d to Standard Output in the following format:

t_1
t_2
\vdots
t_D

Any output that does not follow the above format may result in 0 pointsWA for that test case.

Input Generation

Each integer c_i and s_{d,i} is generated independently and uniformly at random from the integers in the range described in the problem statement.

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192

Sample Output 1

1
17
13
14
13

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case. The final satisfaction with this output is 79325, so the score is 1079325.

Input generator, score calculator, and visualizer

Beginner's Guide

If you don't know what to do, proceed to problem B or C.


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}
import scala.util.Random
import java.util.Date

object Main extends App {
  val startTime = new Date().getTime // to milli seconds

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val D = in.next().toInt
  val c = new Array[Long](26+1)
  val s = Array.ofDim[Long](D+1, 26+1)

  for (i <- 1 to 26) {
    c(i) = in.next().toInt
  }
  for (d <- 1 to D) {
    for (i <- 1 to 26) {
      s(d)(i) = in.next().toInt
    }
  }

  /** functions **/
  def calcScore(t: Array[Int]): Long = {
    val last = new Array[Int](26+1)
    var res = 0L

    for (d <- 1 to D) {
      val ty = t(d)

      res += s(d)(ty)
      last(ty) = d

      for (i <- 1 to 26) {
        res -= c(i) * (d - last(i))
      }
    }

    res
  }

  /** solve **/
  val t = new Array[Int](D+1)
  val last = new Array[Int](26+1)
  for (d <- 1 to D) {
    val (_, ty) =
      s(d).zipWithIndex
        .drop(1)
        .map{ case (s, ty) => (s + c(ty) * (d - last(ty)), ty) }
        .max

    t(d) = ty
    last(ty) = d
  }

  val endTime = 1400
  var currentScore = calcScore(t)
  var bestAns = t.clone
  var bestScore =  currentScore

  val annStartTime = new Date().getTime
  var currentTime = annStartTime

  val T = endTime - annStartTime // 焼きなましにかける時間
  val R = 10000

  while ((new Date().getTime - startTime) < endTime) {
    for (_ <- 1 to 1000) {
      val time = currentTime - annStartTime // 焼きなまし法開始からの時間

      // 遷移を実施
      val d = Random.nextInt(D) + 1
      val ty = Random.nextInt(26) + 1

      val tmp = t(d)
      t(d) = ty

      val nextScore = calcScore(t) // 遷移後のスコアを計算

      // スコアが悪くなったときでも、次の状態に移動する遷移する場合はtrue。
      val ForceNext = T * Random.nextInt(R) < (T-time) * R // １次関数

      if (nextScore > currentScore || ForceNext) {
        // 遷移を適用
        currentScore = nextScore
      }
      else {
        // 遷移を破棄
        t(d) = tmp
      }

      // ベストスコアを保存
      if (currentScore > bestScore) {
        bestScore = currentScore
        bestAns = t.clone // 現在の盤面を渡す
      }
    }
  }

  for (d <- 1 to D) {
    pw.println(t(d))
  }
  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}
import scala.util.Random
import java.util.Date

object Main extends App {
  val startTime = new Date().getTime // to milli seconds

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val D = in.next().toInt
  val c = new Array[Long](26+1)
  val s = Array.ofDim[Long](D+1, 26+1)

  for (i <- 1 to 26) {
    c(i) = in.next().toInt
  }
  for (d <- 1 to D) {
    for (i <- 1 to 26) {
      s(d)(i) = in.next().toInt
    }
  }

  /** functions **/
  def calcScore(t: Array[Int]): Long = {
    val last = new Array[Int](26+1)
    var res = 0L

    for (d <- 1 to D) {
      val ty = t(d)

      res += s(d)(ty)
      last(ty) = d

      for (i <- 1 to 26) {
        res -= c(i) * (d - last(i))
      }
    }

    res
  }

  /** solve **/
  val t = new Array[Int](D+1)
  for (d <- 1 to D) {
    val (_, ty) = s(d).zipWithIndex.max
    t(d) = ty
  }

  val endTime = 1200
  var currentScore = calcScore(t)
  var bestAns = t.clone
  var bestScore =  currentScore

  val annStartTime = new Date().getTime
  var currentTime = annStartTime
  val T = endTime - annStartTime // 焼きなましにかける時間
  val R = 10000

  while ((new Date().getTime - startTime) < endTime) {
    for (_ <- 1 to 1000) {
      val time = currentTime - annStartTime // 焼きなまし法開始からの時間

      // 遷移を実施
      val d = Random.nextInt(D) + 1
      val ty = Random.nextInt(26) + 1

      val tmp = t(d)
      t(d) = ty

      val nextScore = calcScore(t) // 遷移後のスコアを計算

      // スコアが悪くなったときでも、次の状態に移動する遷移する場合はtrue。
      val ForceNext = T * Random.nextInt(R) < (T-time) * R // １次関数

      if (nextScore > currentScore || ForceNext) {
        // 遷移を適用
        currentScore = nextScore
      }
      else {
        // 遷移を破棄
        t(d) = tmp
      }

      // ベストスコアを保存
      if (currentScore > bestScore) {
        bestScore = currentScore
        bestAns = t.clone // 現在の盤面を渡す
      }
    }
  }

  for (d <- 1 to D) {
    pw.println(t(d))
  }
  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}
import scala.util.Random
import java.util.Date

object Main extends App {
  val startTime = new Date().getTime // to milli seconds

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val D = in.next().toInt
  val c = new Array[Long](26+1)
  val s = Array.ofDim[Long](D+1, 26+1)

  for (i <- 1 to 26) {
    c(i) = in.next().toInt
  }
  for (d <- 1 to D) {
    for (i <- 1 to 26) {
      s(d)(i) = in.next().toInt
    }
  }

  /** functions **/
  def calcScore(t: Array[Int]): Long = {
    val last = new Array[Int](26+1)
    var res = 0L

    for (d <- 1 to D) {
      val ty = t(d)

      res += s(d)(ty)
      last(ty) = d

      for (i <- 1 to 26) {
        res -= c(i) * (d - last(i))
      }
    }

    res
  }

  /** solve **/
  val t = new Array[Int](D+1)
  for (d <- 1 to D) {
    t(d) = (d % 26 + 1)
  }

  val endTime = 1400
  var nowScore = calcScore(t)
  while ((new Date().getTime - startTime) < endTime) {
    for (_ <- 1 to 1000) {
      val d = Random.nextInt(D) + 1
      val ty = Random.nextInt(26) + 1

      val tmp = t(d)
      t(d) = ty
      val score = calcScore(t)
      if (score > nowScore) {
        nowScore = score
      }
      else {
        t(d) = tmp
      }
    }
  }

  for (d <- 1 to D) {
    pw.println(t(d))
  }
  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}
import scala.util.Random
import java.util.Date

object Main extends App {
  val startTime = new Date().getTime // to milli seconds

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val D = in.next().toInt
  val c = new Array[Long](26+1)
  val s = Array.ofDim[Long](D+1, 26+1)

  for (i <- 1 to 26) {
    c(i) = in.next().toInt
  }
  for (d <- 1 to D) {
    for (i <- 1 to 26) {
      s(d)(i) = in.next().toInt
    }
  }

  /** functions **/
  def calcScore(t: Array[Int]): Long = {
    val last = new Array[Int](26+1)
    var res = 0L

    for (d <- 1 to D) {
      val ty = t(d)

      res += s(d)(ty)
      last(ty) = d

      for (i <- 1 to 26) {
        res -= c(i) * (d - last(i))
      }
    }

    res
  }

  /** solve **/
  val t = new Array[Int](D+1)
  for (d <- 1 to D) {
    t(d) = (d % 26 + 1)
  }

  val endTime = 1200
  var nowScore = calcScore(t)
  while ((new Date().getTime - startTime) < endTime) {
    for (_ <- 1 to 1000) {
      val d = Random.nextInt(D) + 1
      val ty = Random.nextInt(26) + 1

      val tmp = t(d)
      t(d) = ty
      val score = calcScore(t)
      if (score > nowScore) {
        nowScore = score
      }
      else {
        t(d) = tmp
      }
    }
  }

  for (d <- 1 to D) {
    pw.println(t(d))
  }
  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import scala.collection.mutable.HashMap
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val d  = inputs(0).toInt // 365
  val ci = inputs(1).split(" ").map(_.toInt)
  val sdi = HashMap.empty[Long, Seq[Long]]
  // 日付ごとに、満足度の配列を持つ
  inputs.splitAt(2)._2.zipWithIndex.foreach { case (line, index) =>
    sdi.update(index, line.split(" ").map(_.toLong))
  }

  solve(d, ci, sdi)

  // 1. 単純にでかい数を持っているものを抽出
  // 2. 減少分と上昇分を考慮して最大になる物を選ぶ
  def solve(d: Int, ci: Array[Int], sdi: HashMap[Long, Seq[Long]]): Unit = {
    val last = ArrayBuffer.fill(26)(1)
    var score = 0L
    val range = Range(0, 26, 1)

    (0 until d).foreach { day =>
      val todayValues = sdi(day)
      val max = todayValues.max
      // println(s"max value = $max")
      // TODO: 同じ数値のものが複数ある可能性を考慮
      val maxIndexes = range.map { i =>
        if (max == todayValues(i)) {
          i
        } else {
          -1
        }
      }.filter(v => v != -1)

      val minCiOfTopValue = maxIndexes.map(v => ci(v)).min
      val minCiOfTopValueIndex = range.filter(i => maxIndexes.exists(_ == i) && ci(i) == minCiOfTopValue).min

      // println(s"selected: $i")
      println(minCiOfTopValueIndex + 1)

      last.update(minCiOfTopValueIndex, d)
      score = score + max - range.map(i => ci(i) * (day - last(i)) ).sum
      // println(s"score: $score")
    }

  }

}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val D = in.next().toInt
  val c = new Array[Long](26+1)
  val s = Array.ofDim[Long](D+1, 26+1)

  for (i <- 1 to 26) {
    c(i) = in.next().toInt
  }
  for (d <- 1 to D) {
    for (i <- 1 to 26) {
      s(d)(i) = in.next().toInt
    }
  }

  // val a = new Array[Int](N)
  for (i <- 1 to D) {
    pw.println(7)
  }

  pw.flush()
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M, K = sc.nextInt()
  val as = Array.fill(N)(sc.nextLong()).scanLeft(0L)(_ + _).takeWhile(_ <= K + 1)
  val bs = Array.fill(M)(sc.nextLong()).scanLeft(0L)(_ + _)

  @scala.annotation.tailrec
  def loop(diff: Long, j: Int): Int = if (diff < bs(j)) loop(diff, j - 1) else j

  val (max, _) = as.indices.foldLeft((0, M)) {
    case ((acc, m), i) =>
      val j = loop(K - as(i), m)
      acc.max(i + j) -> j
  }
  println(max)
}

Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M, K = sc.nextInt()
  val as = Array.fill(N)(sc.nextLong()).scanLeft(0L)(_ + _)
  val bs = Array.fill(M)(sc.nextLong()).scanLeft(0L)(_ + _)

  @scala.annotation.tailrec
  def loop(diff: Long, j: Int): Int = if (diff < bs(j)) loop(diff, j - 1) else j

  val counts = for {
    i <- 0 to N
    if as(i) <= K
  } yield i + loop(K - as(i), M)

  println(counts.max)
}


object Main extends App {
  val sc = new FastScanner(System.in)
  val N, M = sc.nextInt()
  val K = sc.nextLong()
  val as = Array.fill(N)(sc.nextLong()).scanLeft(0L)(_ + _).takeWhile(_ <= K + 1)
  val bs = Array.fill(M)(sc.nextLong()).scanLeft(0L)(_ + _).takeWhile(_ <= K + 1)
  val counts = for {
    i <- as.indices
    j <- bs.indices
    if as(i) + bs(j) <= K
  } yield i + j
  println(counts.max)

  class FastScanner(in: java.io.InputStream) {
    val buffer = new Array[Byte](1024)
    var length = 0
    var p = 0

    def hasNextByte: Boolean =
      if (p < length) true
      else {
        p = 0
        length = in.read(buffer)
        if (length == 0) false else true
      }

    def readByte: Int = if (hasNextByte) buffer({ p += 1; p - 1 }) else -1

    def isPrintable(n: Int): Boolean = 33 <= n && n <= 126

    def skip(): Unit = while (hasNextByte && !isPrintable(buffer(p))) p += 1

    def hasNext: Boolean = {
      skip()
      hasNextByte
    }

    def next(): String = {
      if (!hasNext) throw new NoSuchElementException
      val sb = new java.lang.StringBuilder
      var temp = readByte
      while (isPrintable(temp)) {
        sb.appendCodePoint(temp)
        temp = readByte
      }
      sb.toString
    }

    def nextInt(): Int = Math.toIntExact(nextLong())

    def nextInts(n: Int): Array[Int] = {
      val ar = new Array[Int](n)
      for (i <- 0 until n) ar(i) = nextInt()
      ar
    }

    def nextLong(): Int = {
      if (!hasNext) throw new NoSuchElementException
      var minus = false
      var temp = readByte
      if (temp == '-') {
        minus = true
        temp = readByte
      }
      if (temp < '0' || '9' < temp) throw new NumberFormatException
      var n = 0
      while (isPrintable(temp)) {
        if ('0' <= temp && temp <= '9') {
          n *= 10
          n += temp - '0'
        }
        temp = readByte
      }
      if (minus) -n else n
    }
  }

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextInt()
  val K = sc.nextLong()
  val as = Array.fill(N)(sc.nextLong()).scanLeft(0L)(_ + _).takeWhile(_ <= K + 1)
  val bs = Array.fill(M)(sc.nextLong()).scanLeft(0L)(_ + _).takeWhile(_ <= K + 1)
  val counts = for {
    i <- as.indices
    j <- bs.indices
    if as(i) + bs(j) <= K
  } yield i + j
  println(counts.max)
}


import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Long]=Nil):List[Long] =
    if (c > 0) readALine(c-1, sc.nextLong::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N,M = sc.nextInt
  val K = sc.nextLong
  val Ai = readALine(N)
  val Bi = readALine(M)
  val Zero:Long = 0L

  def find(array:Array[Long], key:Long):Int = {
    require(!array.isEmpty,"Array must have elements.")
    def iter(l:Int, r:Int):Int = {
      if (l == r) if (array(l) > key) l-1 else l
      val bound = (l+r)>>1
      // if (bound > 200000) println(s"l:$l r:$r bound:$bound key:$key")
      array(bound) match {
        case v if v > key => if (array(bound-1) < key) bound-1 else iter(l, bound-1)
        case v if v < key => if (array(bound+1) > key) bound else iter(bound+1, r)
        case _ => bound
      }
    }

    val maxIdx = array.length-1
    key match {
      case k if k > array(maxIdx) => maxIdx
      case k if k < array(0) => -1
      case _ => iter(0, array.length-1)
    }
  }

  def solver():Int = {
    def acumulate(list:List[Long], ac:List[Long]):List[Long] =
      if (list.isEmpty) ac
      else if (ac.isEmpty) acumulate(list.tail,list.head::ac)
      else acumulate(list.tail,(ac.head+list.head)::ac)
    val cumAi = acumulate(Zero::Ai, Nil).reverse.toArray
    val cumBi = acumulate(Zero::Bi, Nil).reverse.toArray

    // println(cumAi.mkString(","))
    // println(cumBi.mkString(","))

    def iter(i:Int, max:Int):Int = {
      if (i < cumAi.length && cumAi(i) <= K) {
        val j = find(cumBi, K - cumAi(i))
        // println(s"i:$i j:$j max:$max")
        if (i+j > max) iter(i+1, i+j) else iter(i+1, max)
      } else max
    }
    iter(0, 0)
  }

  println(solver())

}


import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Long]=Nil):List[Long] =
    if (c > 0) readALine(c-1, sc.nextLong::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N,M = sc.nextInt
  val K = sc.nextLong
  val Ai = readALine(N)
  val Bi = readALine(M)
  val Zero:Long = 0L

  def find(array:Array[Long], key:Long):Int = {
    require(!array.isEmpty,"Array must have elements.")
    def iter(l:Int, r:Int):Int = {
      if (l == r) if (array(l) > key) l-1 else l
      val bound = (l+r)>>1
      // println(s"l:$l r:$r bound:$bound key:$key")
      array(bound) match {
        case v if v > key => if (array(bound-1) < key) bound-1 else iter(l-1, bound)
        case v if v < key => if (array(bound+1) > key) bound else iter(bound, r+1)
        case _ => bound
      }
    }

    val maxIdx = array.length-1
    key match {
      case k if k > array(maxIdx) => maxIdx
      case k if k < array(0) => -1
      case _ => iter(0, array.length-1)
    }
  }

  def solver():Int = {
    def acumulate(list:List[Long], ac:List[Long]):List[Long] =
      if (list.isEmpty) ac
      else if (ac.isEmpty) acumulate(list.tail,list.head::ac)
      else acumulate(list.tail,(ac.head+list.head)::ac)
    val cumAi = acumulate(Zero::Ai, Nil).reverse.toArray
    val cumBi = acumulate(Zero::Bi, Nil).reverse.toArray

    println(cumAi.mkString(","))
    println(cumBi.mkString(","))

    def iter(i:Int, max:Int):Int = {
      if (i < cumAi.length && cumAi(i) <= K) {
        val j = find(cumBi, K - cumAi(i))
        println(s"i:$i j:$j max:$max")
        if (i+j > max) iter(i+1, i+j) else iter(i+1, max)
      } else max
    }
    iter(0, 0)
  }

  println(solver())

}


import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Int]=Nil):List[Int] =
    if (c > 0) readALine(c-1, sc.nextInt::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N,M,K = sc.nextInt
  val Ai = readALine(N)
  val Bi = readALine(M)

  def find(array:Array[Int], key:Int):Int = {
    require(!array.isEmpty,"Array must have elements.")
    def iter(l:Int, r:Int):Int = {
      if (l == r) if (array(l) > key) l-1 else l
      val bound = (l+r)>>1
      // println(s"l:$l r:$r bound:$bound key:$key")
      array(bound) match {
        case v if v > key => if (array(bound-1) < key) bound-1 else iter(l-1, bound)
        case v if v < key => if (array(bound+1) > key) bound else iter(bound, r+1)
        case _ => bound
      }
    }

    val maxIdx = array.length-1
    key match {
      case k if k > array(maxIdx) => maxIdx
      case k if k < array(0) => -1
      case _ => iter(0, array.length-1)
    }
  }

  def solver():Int = {
    def acumulate(list:List[Int], ac:List[Int]):List[Int] =
      if (list.isEmpty) ac
      else if (ac.isEmpty) acumulate(list.tail,list.head::ac)
      else acumulate(list.tail,(ac.head+list.head)::ac)
    val cumAi = acumulate(Ai, Nil).reverse.toArray
    val cumBi = acumulate(Bi, Nil).reverse.toArray

    // println(cumAi.mkString(","))
    // println(cumBi.mkString(","))

    def iter(i:Int, max:Int):Int = {
      if (i < cumAi.length && cumAi(i) < K) {
        val j = find(cumBi, K - cumAi(i))
        // println(s"i:$i j:$j max:$max")
        if (i+j+2 > max) iter(i+1, i+j+2) else iter(i+1, max)
      } else max
    }
    iter(0, 0)
  }

  println(solver())

}


import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Int]=Nil):List[Int] =
    if (c > 0) readALine(c-1, sc.nextInt::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N,M,K = sc.nextInt
  val Ai = readALine(N)
  val Bi = readALine(M)

  def find(array:Array[Int], key:Int):Int = {
    def iter(l:Int, r:Int):Int = {
      if (l == r) if (array(l) > key) l-1 else l
      else {
        val bound = (l+r)>>1
        if (array(bound) > key) iter(l, bound-1)
        else if (array(bound) < key) iter(bound+1, r)
        else bound
      }
    }
    val maxIdx = array.length-1
    if (array(maxIdx) < key) maxIdx
    else if (array(0) > key) -1
    else iter(0, array.length-1)
  }

  def solver():Int = {
    def acumulate(list:List[Int], ac:List[Int]):List[Int] =
      if (list.isEmpty) ac
      else if (ac.isEmpty) acumulate(list.tail,list.head::ac)
      else acumulate(list.tail,(ac.head+list.head)::ac)
    val cumAi = acumulate(Ai, Nil).reverse.toArray
    val cumBi = acumulate(Bi, Nil).reverse.toArray

    // println(cumAi.mkString(","))
    // println(cumBi.mkString(","))

    def iter(i:Int, max:Int):Int = {
      if (i < cumAi.length && cumAi(i) < K) {
        val j = find(cumBi, K - cumAi(i))
        // println(s"i:$i j:$j max:$max")
        if (i+j+2 > max) iter(i+1, i+j+2) else iter(i+1, max)
      } else max
    }
    iter(0, 0)
  }

  println(solver())

}