// import scala.io.{StdIn => in}
import java.io._;

object Main extends App {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(h, w) = in.readLine.split(" ").map(_.toInt)
  val n = h * w

  val arr = Iterator.continually(in.readLine)
    .take(h)
    .map(_.toArray)
    .toArray

  def bfs(grid:Array[Array[Char]]):Int = {
    val dist = Array.ofDim[Int](h, w)
    var distMax = 0
    val dx = Array( 0, 1, 0,-1)
    val dy = Array( 1, 0,-1, 0)
    // val que = collection.mutable.Queue.empty[(Int,Int)]
    val que = new java.util.ArrayDeque[Tuple2[Int,Int]]()
    for {
      i <- 0 until h
      j <- 0 until w
      if grid(i)(j) == '#'
    } que.offer(Tuple2(i, j))

    while(!que.isEmpty) {
      val(y,x) = que.poll

      for(i <- 0 until 4) {
        val ny = y + dy(i)
        val nx = x + dx(i)
        if(0 <= ny && ny < h && 0 <= nx && nx < w && grid(ny)(nx) != '#') {
          val d = dist(y)(x) + 1
          dist(ny)(nx) = d
          grid(ny)(nx) = '#'
          que.offer(Tuple2(ny, nx))
          if(distMax < d) distMax = d
        }
      }
    }
    distMax
  }

  val ans = bfs(arr)
  println(ans)
}


// import scala.io.{StdIn => in}
import java.io._;

object Main extends App {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(h, w) = in.readLine.split(" ").map(_.toInt)
  val n = h * w

  val arr = Iterator.continually(in.readLine)
    .take(h)
    .map(_.map(ch => if(ch == '#') true else false).toArray)
    .toArray

  def bfs(grid:Array[Array[Boolean]]):Int = {
    val dist = Array.ofDim[Int](h, w)
    var distMax = 0
    val dx = Array( 0, 1, 0,-1)
    val dy = Array( 1, 0,-1, 0)
    val que = collection.mutable.Queue.empty[(Int,Int)]
    for {
      i <- 0 until h
      j <- 0 until w
      if grid(i)(j)
    } que += Tuple2(i, j)

    while(que.nonEmpty) {
      val(y,x) = que.dequeue

      for(i <- 0 until 4) {
        val ny = y + dy(i)
        val nx = x + dx(i)
        if(0 <= ny && ny < h && 0 <= nx && nx < w && !grid(ny)(nx)) {
          val d = dist(y)(x) + 1
          dist(ny)(nx) = d
          grid(ny)(nx) = true
          que += Tuple2(ny, nx)
          if(distMax < d) distMax = d
        }
      }
    }
    distMax
  }

  val ans = bfs(arr)
  println(ans)
}

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

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 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.


object Main extends App {
  val start = System.nanoTime
  //println(System.currentTimeMillis - start)
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail
  //println(ls)
  //val q = scala.collection.mutable.Queue[(Int,Int)]()
  var q = scala.collection.mutable.LinkedHashSet[(Int,Int)]()
  val ls0indices = ls(0).indices
  //println(System.currentTimeMillis - start)
  val tt = ls.indices.map{ y =>
    (Int.MaxValue +:
     ls0indices.map{ x =>
      if(ls(y)(x) == '#'){
        q.add((x-1+1, y+1))
        q.add((x-1+1, y+1))
        q.add((x+1, y+1+1))
        q.add((x+1, y+1+1))
        0
      }else{
        Int.MaxValue - 1
      }
    } :+ Int.MaxValue).toArray
  }
  val ww = tt(0).map(e => Int.MaxValue)
  val t = (ww +: tt :+ ww).toArray
  //t.map(e => println(e.mkString(",")))
  var max = 0
  //private def func(n:Int):Int
  //println(System.currentTimeMillis - start)
  while(q.nonEmpty){
    val elapsed = System.nanoTime - start
    if(elapsed > 100000000L){ println(max); sys.exit()}
    val (x,y) = q.head
    q = q.tail
    if(t(y)(x) == Int.MaxValue-1){
      val inc = 1 + Math.min(
        Math.min(t(y-1)(x), t(y)(x-1)),
        Math.min(t(y+1)(x), t(y)(x+1)))
      //println(x,y,t(y)(x))
      t(y)(x) = inc
      max = Math.max(max, inc)
      if(t(y-1)(x) == Int.MaxValue-1) q.add((x,y-1))
      if(t(y+1)(x) == Int.MaxValue-1) q.add((x,y+1))
      if(t(y)(x-1) == Int.MaxValue-1) q.add((x-1,y))
      if(t(y)(x+1) == Int.MaxValue-1) q.add((x+1,y))
    }
  }
  //println(System.currentTimeMillis - start)
  println(max)
}


object Main extends App {
  val start = System.nanoTime
  //println(System.currentTimeMillis - start)
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail
  //println(ls)
  //val q = scala.collection.mutable.Queue[(Int,Int)]()
  var q = scala.collection.mutable.LinkedHashSet[(Int,Int)]()
  val ls0indices = ls(0).indices
  //println(System.currentTimeMillis - start)
  val tt = ls.indices.map{ y =>
    (Int.MaxValue +:
     ls0indices.map{ x =>
      if(ls(y)(x) == '#'){
        q.add((x-1+1, y+1))
        q.add((x-1+1, y+1))
        q.add((x+1, y+1+1))
        q.add((x+1, y+1+1))
        0
      }else{
        Int.MaxValue - 1
      }
    } :+ Int.MaxValue).toArray
  }
  val ww = tt(0).map(e => Int.MaxValue)
  val t = (ww +: tt :+ ww).toArray
  //t.map(e => println(e.mkString(",")))
  var max = 0
  //private def func(n:Int):Int
  //println(System.currentTimeMillis - start)
  while(q.nonEmpty){
    val elapsed = System.nanoTime - start
    if(elapsed > 300000000L){ println(max); sys.exit()}
    val (x,y) = q.head
    q = q.tail
    if(t(y)(x) == Int.MaxValue-1){
      val inc = 1 + Math.min(
        Math.min(t(y-1)(x), t(y)(x-1)),
        Math.min(t(y+1)(x), t(y)(x+1)))
      //println(x,y,t(y)(x))
      t(y)(x) = inc
      max = Math.max(max, inc)
      if(t(y-1)(x) == Int.MaxValue-1) q.add((x,y-1))
      if(t(y+1)(x) == Int.MaxValue-1) q.add((x,y+1))
      if(t(y)(x-1) == Int.MaxValue-1) q.add((x-1,y))
      if(t(y)(x+1) == Int.MaxValue-1) q.add((x+1,y))
    }
  }
  //println(System.currentTimeMillis - start)
  println(max)
}


object Main extends App {
  val start = System.currentTimeMillis
  //println(System.currentTimeMillis - start)
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail
  //println(ls)
  //val q = scala.collection.mutable.Queue[(Int,Int)]()
  var q = scala.collection.mutable.LinkedHashSet[(Int,Int)]()
  val ls0indices = ls(0).indices
  //println(System.currentTimeMillis - start)
  val tt = ls.indices.map{ y =>
    (Int.MaxValue +:
     ls0indices.map{ x =>
      if(ls(y)(x) == '#'){
        q.add((x-1+1, y+1))
        q.add((x-1+1, y+1))
        q.add((x+1, y+1+1))
        q.add((x+1, y+1+1))
        0
      }else{
        Int.MaxValue - 1
      }
    } :+ Int.MaxValue).toArray
  }
  val ww = tt(0).map(e => Int.MaxValue)
  val t = (ww +: tt :+ ww).toArray
  //t.map(e => println(e.mkString(",")))
  var max = 0
  //private def func(n:Int):Int
  //println(System.currentTimeMillis - start)
  while(q.nonEmpty){
    val elapsed = System.currentTimeMillis - start
    if(elapsed > 100){ println(max); sys.exit()}
    val (x,y) = q.head
    q = q.tail
    if(t(y)(x) == Int.MaxValue-1){
      val inc = 1 + Math.min(
        Math.min(t(y-1)(x), t(y)(x-1)),
        Math.min(t(y+1)(x), t(y)(x+1)))
      //println(x,y,t(y)(x))
      t(y)(x) = inc
      max = Math.max(max, inc)
      if(t(y-1)(x) == Int.MaxValue-1) q.add((x,y-1))
      if(t(y+1)(x) == Int.MaxValue-1) q.add((x,y+1))
      if(t(y)(x-1) == Int.MaxValue-1) q.add((x-1,y))
      if(t(y)(x+1) == Int.MaxValue-1) q.add((x+1,y))
    }
  }
  //println(System.currentTimeMillis - start)
  println(max)
}


object Main extends App {
  val start = System.currentTimeMillis
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail
  //println(ls)
  //val q = scala.collection.mutable.Queue[(Int,Int)]()
  var q = scala.collection.mutable.LinkedHashSet[(Int,Int)]()
  val ls0indices = ls(0).indices
  val tt = ls.indices.map{ y =>
    (Int.MaxValue +:
     ls0indices.map{ x =>
      if(ls(y)(x) == '#'){
        q.add((x-1+1, y+1))
        q.add((x-1+1, y+1))
        q.add((x+1, y+1+1))
        q.add((x+1, y+1+1))
        0
      }else{
        Int.MaxValue - 1
      }
    } :+ Int.MaxValue).toArray
  }
  val ww = tt(0).map(e => Int.MaxValue)
  val t = (ww +: tt :+ ww).toArray
  //t.map(e => println(e.mkString(",")))
  var max = 0
  //private def func(n:Int):Int
  while(q.nonEmpty){
    val elapsed = System.currentTimeMillis - start
    if(elapsed > 900){ println(max); sys.exit()}
    val (x,y) = q.head
    q = q.tail
    if(t(y)(x) == Int.MaxValue-1){
      val inc = 1 + Math.min(
        Math.min(t(y-1)(x), t(y)(x-1)),
        Math.min(t(y+1)(x), t(y)(x+1)))
      //println(x,y,t(y)(x))
      t(y)(x) = inc
      max = Math.max(max, inc)
      if(t(y-1)(x) == Int.MaxValue-1) q.add((x,y-1))
      if(t(y+1)(x) == Int.MaxValue-1) q.add((x,y+1))
      if(t(y)(x-1) == Int.MaxValue-1) q.add((x-1,y))
      if(t(y)(x+1) == Int.MaxValue-1) q.add((x+1,y))
    }
  }
  println(max)
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail
  //println(ls)
  //val q = scala.collection.mutable.Queue[(Int,Int)]()
  var q = scala.collection.mutable.LinkedHashSet[(Int,Int)]()
  val ls0indices = ls(0).indices
  val tt = ls.indices.map{ y =>
    (Int.MaxValue +:
     ls0indices.map{ x =>
      if(ls(y)(x) == '#'){
        q.add((x-1+1, y+1))
        q.add((x-1+1, y+1))
        q.add((x+1, y+1+1))
        q.add((x+1, y+1+1))
        0
      }else{
        Int.MaxValue - 1
      }
    } :+ Int.MaxValue).toArray
  }
  val ww = tt(0).map(e => Int.MaxValue)
  val t = (ww +: tt :+ ww).toArray
  //t.map(e => println(e.mkString(",")))
  var max = 0
  //private def func(n:Int):Int
  while(q.nonEmpty){
    val (x,y) = q.head
    q = q.tail
    if(t(y)(x) == Int.MaxValue-1){
      val inc = 1 + Math.min(
        Math.min(t(y-1)(x), t(y)(x-1)),
        Math.min(t(y+1)(x), t(y)(x+1)))
      //println(x,y,t(y)(x))
      t(y)(x) = inc
      max = Math.max(max, inc)
      if(t(y-1)(x) == Int.MaxValue-1) q.add((x,y-1))
      if(t(y+1)(x) == Int.MaxValue-1) q.add((x,y+1))
      if(t(y)(x-1) == Int.MaxValue-1) q.add((x-1,y))
      if(t(y)(x+1) == Int.MaxValue-1) q.add((x+1,y))
    }
  }
  println(max)
}


import scala.util.control.Breaks

object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toStream
    println(solve(lines))
  }

  def solve(lines: Seq[String]): String = {
    val Array(h, w) = lines.head.split(" ").map(_.toInt)
    val tiles = lines.tail.take(h).map(_.split("").filter(_.length > 0).take(w)).toArray
    debug(h, w, tiles)

    var counter = 0
    var blacks = tiles.map(_.count(_ == "#")).sum
    while (blacks < h * w) {
      val _tiles = tiles.map(_.map(x => x).toIndexedSeq).toIndexedSeq
      val whites = _tiles.map(x => x.zipWithIndex.filter(_._1 == ".").map(_._2)).filter(_.nonEmpty).zipWithIndex.flatMap(x => x._1.map(y => (x._2, y)))
      whites.foreach { case (i, j) =>
        if (i == 0) {
          if (j == 0) {
            blacks += paint(tiles, _tiles, i, j, Seq(1, 2))
          } else if (j == w - 1) {
            blacks += paint(tiles, _tiles, i, j, Seq(2, 3))
          } else {
            blacks += paint(tiles, _tiles, i, j, Seq(1, 2, 3))
          }
        } else if (i == h - 1) {
          if (j == 0) {
            blacks += paint(tiles, _tiles, i, j, Seq(0, 1))
          } else if (j == w - 1) {
            blacks += paint(tiles, _tiles, i, j, Seq(0, 3))
          } else {
            blacks += paint(tiles, _tiles, i, j, Seq(0, 1, 3))
          }
        } else {
          if (j == 0) {
            blacks += paint(tiles, _tiles, i, j, Seq(0, 1, 2))
          } else if (j == w - 1) {
            blacks += paint(tiles, _tiles, i, j, Seq(0, 2, 3))
          } else {
            blacks += paint(tiles, _tiles, i, j, Seq(0, 1, 2, 3))
          }
        }
      }
      counter += 1
    }

    val result = counter.toString
    result
  }

  def paint(tiles: Array[Array[String]], copy: Seq[Seq[String]], i: Int, j: Int, directions: Seq[Int]): Int = {
    var result = 0
    val br = new Breaks
    br.breakable {
      directions.foreach { d =>
        if (d == 0) {
          if (copy(i - 1)(j) == "#") {
            tiles(i)(j) = "#"
            result = 1
          }
        } else if (d == 1) {
          if (copy(i)(j + 1) == "#") {
            tiles(i)(j) = "#"
            result = 1
          }
        } else if (d == 2) {
          if (copy(i + 1)(j) == "#") {
            tiles(i)(j) = "#"
            result = 1
          }
        } else {
          if (copy(i)(j - 1) == "#") {
            tiles(i)(j) = "#"
            result = 1
          }
        }
        if (result != 0) br.break()
      }
    }
    result
  }

  private def debug(x: Any): Unit = {
    if (System.getenv("LOCAL_DEBUG") != null)
      println(x)
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    val Array(h, w) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var A = Array.fill[Boolean](h+2, w+2)(true)

    var wc = 0
    (1 to h) foreach { i =>
      scala.io.StdIn.readLine().zipWithIndex.foreach { case (c, j) =>
        A(i)(j+1) = if (c == '.') {
          wc += 1
          true
        } else false
      }
    }

    var c = 0
    while (wc > 0) {
      val cloneA = A.map(_.clone()).clone()
      for {
        i <- 1 to h
        j <- 1 to w
        if A(i)(j)
        if !A(i)(j-1) || !A(i)(j+1) || !A(i-1)(j) || !A(i+1)(j)
      } {
        wc -= 1
        cloneA(i)(j) = false
      }
      c += 1
      A = cloneA
    }

    println(c)
  }

}


import scala.util.control.Breaks

object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toStream
    println(solve(lines))
  }

  def solve(lines: Seq[String]): String = {
    val Array(h, w) = lines.head.split(" ").map(_.toInt)
    val tiles = lines.tail.take(h).map(_.split("").filter(_.length > 0).take(w)).toArray
    debug(h, w, tiles)

    var counter = 0
    val br = new Breaks
    br.breakable {
      while (true) {
        val _tiles = tiles.map(_.map(x => x).toSeq).toSeq
        (0 until h).foreach { i =>
          (0 until w).foreach { j =>
            if (i == 0) {
              if (j == 0) {
                paint(tiles, _tiles, i, j, Seq(1, 2))
              } else if (j == w - 1) {
                paint(tiles, _tiles, i, j, Seq(2, 3))
              } else {
                paint(tiles, _tiles, i, j, Seq(1, 2, 3))
              }
            } else if (i == h - 1) {
              if (j == 0) {
                paint(tiles, _tiles, i, j, Seq(0, 1))
              } else if (j == w - 1) {
                paint(tiles, _tiles, i, j, Seq(0, 3))
              } else {
                paint(tiles, _tiles, i, j, Seq(0, 1, 3))
              }
            } else {
              if (j == 0) {
                paint(tiles, _tiles, i, j, Seq(0, 1, 2))
              } else if (j == w - 1) {
                paint(tiles, _tiles, i, j, Seq(0, 2, 3))
              } else {
                paint(tiles, _tiles, i, j, Seq(0, 1, 2, 3))
              }
            }
          }
        }
        counter += 1
        if (tiles.map(_.count(_ == "#")).sum == h * w) br.break()
      }
    }

    val result = counter.toString
    result
  }

  def paint(tiles: Array[Array[String]], copy: Seq[Seq[String]], i: Int, j: Int, directions: Seq[Int]): Unit = {
    directions.foreach { d =>
      if (tiles(i)(j) != "#") {
        if (d == 0) {
          if (copy(i - 1)(j) == "#") tiles(i)(j) = "#"
        } else if (d == 1) {
          if (copy(i)(j + 1) == "#") tiles(i)(j) = "#"
        } else if (d == 2) {
          if (copy(i + 1)(j) == "#") tiles(i)(j) = "#"
        } else {
          if (copy(i)(j - 1) == "#") tiles(i)(j) = "#"
        }
      }
    }
  }

  private def debug(x: Any): Unit = {
    if (System.getenv("LOCAL_DEBUG") != null)
      println(x)
  }
}


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

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

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

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

  def solve(): Unit = {
    val H, W = ni()
    val g = nm_c(H, W)
    val V = Array.fill[Int](H * W)(1e9.toInt)

    REP(H) { h =>
      REP(W) { w =>
        if (g(h)(w) == '#') V(h * W + w) = 0
      }
    }

    val D = Array(
      Array(-1, 0), Array(1, 0), Array(0, -1), Array(0, 1)
    )
    val queue = new Queue[Int](H * W * 4)

    def spread(h: Int, w: Int): Unit = {
      REP(4) { k =>
        val dh = D(k)(0)
        val dw = D(k)(1)
        if (0 <= h + dh && h + dh < H && 0 <= w + dw && w + dw < W && g(h + dh)(w + dw) == '.') {
          val u = (h + dh) * W + w + dw
          val v = h * W + w
          debug(s"h:$h dh:$dh w:$w dw:$dw u:$u")
          if (V(u) > V(v) + 1) {
            queue += u
            V(u) = V(v) + 1
          }
//          g(h + dh)(w + dw) = '#'
        }
      }
    }

    REP(H) { h =>
      REP(W) { w =>
        if (g(h)(w) == '#') {
          spread(h, w)
        }
      }
    }

    while(queue.nonEmpty) {
      val v = queue.dequeue()
      val h = v / W
      val w = v % W
      spread(h, w)
    }

    val ans = V.max
    out.println(ans)
  }

  class Queue[A: ClassTag](n: Int) {
    private val as = Array.ofDim[A](n)
    var p = 0
    var cur = 0

    def +=(a: A): Unit = {
      as(p) = a
      p += 1
    }

    def dequeue(): A = {
      val a = as(cur)
      cur += 1
      a
    }

    def head: A = as(cur)

    def apply(i: Int): A = as(cur + i)

    def length: Int = p - cur
    def isEmpty: Boolean = length == 0
    def nonEmpty: Boolean = !isEmpty

    def mkString(delimiter: String = ""): String = as.slice(cur, cur + length).mkString(delimiter)
  }

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

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

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

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

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

  def debugDim(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m.length) { i =>
      debug(m(i))
    }
  }

  def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }

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

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

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

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

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

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

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

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


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

  val Array(h, w) = readLine.trim.split(' ').map(_.toInt)
  val state = Array.fill(h){readLine.trim.toCharArray.map(_ == '#')}
  val memo = Array.fill(h){Array.fill(w){-1}}
  val queue = mutable.Queue[Point]()
  for (p ← (0 until h).flatMap{y ⇒ (0 until w).filter{x ⇒ state(y)(x)}.map{x ⇒ Point(x, y)}}) {
    queue.enqueue(p)
    memo(p.y)(p.x) = 0
  }
  while(queue.nonEmpty) {
    val current = queue.dequeue()
    for (next ← current.neighbors if (0 until h).contains(next.y) && (0 until w).contains(next.x) && !state(next.y)(next.x)) if (!state(next.y)(next.x)) {
      memo(next.y)(next.x) = memo(current.y)(current.x) + 1
      state(next.y)(next.x) = true
      queue.enqueue(next)
    }
  }
  println(memo.map{_.max}.max)

  case class Point(x: Int, y: Int){
    def neighbors = List(Point(x + 1, y), Point(x - 1, y), Point(x, y + 1), Point(x, y - 1))
  }
}


import scala.io.StdIn._

object Main extends App {

  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  def solve() = {
    val l = Array.fill(n)(0)
    val r = Array.fill(n)(0)

    for(i <- 0 until n-1) l(i+1) = gcd(l(i), A(i))
    for(i <- n-1 until 0 by-1) r(i-1) = gcd(r(i), A(i))

    (0 until n).foldLeft(1) { (acc, i) =>
      Math.max(acc, gcd(l(i), r(i)))
    }
  }

  def gcd(x: Int, y: Int): Int = {
    if(y == 0) x
    else gcd(y, x % y)
  }

  println(solve())

}

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


import scala.io.StdIn._

object Main extends App {

  val n = readInt()
  val A = readLine().split(" ").map(_.toLong)

  def solve() = {
    val max = A.max
    A.map(calcGCD(_, max)).sorted
  }

  def calcGCD(x: Long, y: Long): Long = {
    if(y == 0) x
    else calcGCD(y, x % y)
  }

  println(solve())

}


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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new GCDPrefix(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val N: Int = ni()
    val A: Array[Int] = na(N)

    val B: Array[Int] = Array.ofDim[Int](N+1)
    val C: Array[Int] = Array.ofDim[Int](N+1)

    B(0) = 0
    REP(N) { i =>
      B(i+1) = gcd(A(i), B(i))
    }
    C(N) = 0
    REP_r(N) { i =>
      C(i) = gcd(C(i+1), A(i))
    }

    var ret = B(N)

    REP(N) { i =>
      ret = Math.max(ret, gcd(B(i), C(i+1)))
    }
    out.println(ret)
  }

  def gcd(x: Int, y: Int): Int = {
    if(x == 0) y
    if(y == 0) x
    else gcd(y, x%y)
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val N = sc.nextInt()
    val A = Array.fill(N)(sc.nextInt())

    // 一つ選んで書き換えた際の
    // 最大公約数の最大値
    // ある数を選択した時, その数を書き換えて最大の公約数を作る場合
    // それ以外の数で作られる最大公約数のよりも大きな最大公約数を作ることが
    // できないので、それ以外の数で作られる最大公約数がその数を選択した
    // 場合における最大公約数となる

    // 選んだ場合と選ばなかった場合
    // 単に計算すると, N - 1個の整数について最大公約数を求め
    // それをN回繰り返すことになる。
    // のでO(N^2)以上にはなる.　これでは間に合わない
    // Ai を選択する時
    // A0 - Ai-1 の最大公約数
    // Ai+1 - AN の最大公約数
    // がわかっていれば, A0 - Ai-1 の最大公約数 と Ai+1 - ANの最大公約数の
    // 最大公約数を求めれば求めたい数になる
    def gcd(a: Long, b: Long): Long =
      if (a % b == 0) b
      else gcd(b, a % b)

    def solve(N: Int, A: Array[Int]): Long = {
      def calcLeftGCD(): Array[Long] = {
        val left = new Array[Long](N)
        def loop(i: Int, acm: Long): Unit =
          if (i < N - 1) {
            left(i) = gcd(acm, A(i).toLong)
            loop(i + 1, left(i))
          }
        left(0) = A(0)
        loop(1, A(0))
        left
      }
      def calcRightGCD(): Array[Long] = {
        val right = new Array[Long](N)
        def loop(i: Int, acm: Long): Unit =
          if (i > 0) {
            right(i) = gcd(acm, A(i).toLong)
            loop(i - 1, right(i))
          }
        right(N - 1) = A(N - 1)
        loop(N - 2, right(N - 1))
        right
      }
      val left = calcLeftGCD()
      val right = calcRightGCD()

      def loop(i: Int, max: Long): Long =
        if (i < N) {
          loop(i + 1, max max {
            if (i > 0 && i < N - 1) gcd(left(i - 1), right(i + 1))
            else if (i > 0) left(i - 1)
            else right(i + 1)
          })
        } else max
      loop(0, 0)
    }

    println(solve(N, A))
  }

}


import java.util.Scanner
object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val as = Array.fill(n)(sc.nextInt)
  def gcd(l: Int, r: Int): Int = if (r == 0) l else if (l % r == 0) r else gcd(r, l % r)
  val gcdsL = as.scanLeft(0)((z, a) => gcd(z, a))
  val gcdsR = as.scanRight(0)((a, z) => gcd(z, a))
  println(gcdsL.zip(gcdsR.tail).map(z => gcd(z._1, z._2)).max)
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine.toInt
    val as = StdIn.readLine.split(" ").map(_.toInt)

    //(0 +: as :+ 0).foreach {println}  // 別にこれいらないか

    val l = Array.fill(n + 2)(0)
    val r = Array.fill(n + 2)(0)

    for (i <- 1 to n) {
      l(i) = gcd(l(i - 1), as(i - 1))
    }

    for (i <- n to 1 by -1) {
      r(i) = gcd(r(i + 1), as(i - 1))
    }

    println((1 to n).toList.map(i => gcd(l(i - 1), r(i + 1))).max)
  }

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


import scala.annotation.tailrec

object Main{
	@tailrec
	def gcd(a:Int,b:Int):Int ={
		if(b==0) a else gcd(b,a % b)
	}
	def main(args:Array[String]){
		val s = new java.util.Scanner(System.in)
		val n = s.nextInt
		val a = Array.fill(n)(s.nextInt)
		val l,r = Array.fill(n + 2)(0)
		for(i <- 1 to n)
			l(i) = gcd(l(i - 1),a(i - 1))
		for(i <- n to 1 by -1)
			r(i) = gcd(r(i + 1),a(i - 1))
		println((1 to n).map(i => gcd(l(i - 1),r(i + 1))).max)
	}
}


import scala.annotation.tailrec

object Main{
	@tailrec
	def gcd(a:Int,b:Int):Int ={
		if(b==0) a
		else if(a % b == 0) b else gcd(b,a % b)
	}
	def main(args:Array[String]){
		val s = new java.util.Scanner(System.in)
		val n = s.nextInt
		val a = Array.fill(n)(s.nextInt)
		val l,r = Array.fill(n + 2)(0)
		for(i <- 1 to n)
			l(i) = gcd(l(i - 1),a(i - 1))
		for(i <- n to 1 by -1)
			r(i) = gcd(r(i + 1),a(i - 1))
		println((1 to n).map(i => gcd(l(i - 1),r(i + 1))).max)
	}
}


object Main extends App {

  import scala.annotation.tailrec
  import scala.math.max

  val n = scala.io.StdIn.readLine.toInt
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  @tailrec
  def gcd(x: Int, y: Int): Int = {
    if (y == 0) {
      x
    } else
      gcd(y, x % y)
  }

  var rr = new Array[Int](n)
  var ll = new Array[Int](n)
  rr(0) = a(0)
  ll(n - 1) = a.last

  (1 until n).foreach { i =>
    rr(i) = gcd(rr(i - 1), a(i))

    ll(n - 1 - i) = gcd(ll(n - i), a(n - 1 - i))

  }

  var ans = List(rr(1), ll(1)).max

  rr = rr.reverse

  (1 until n - 1).foreach { i =>
    ans = max(ans, gcd(rr(i - 1), ll(i + 1)))
  }

  println(ans)
}


object Main extends App {

  import scala.math.max
  import scala.annotation.tailrec

  val n = scala.io.StdIn.readLine.toInt
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  @tailrec
  def gcd(x: Int, y: Int): Int = {
    if (y == 0) {
      x
    } else
      gcd(y, x % y)
  }

  var rr = List(a(0))
  var ll = List(a.last)
  (1 until n).foreach { i =>
    rr = gcd(rr.head, a(i)) :: rr

    ll = gcd(ll.head, a(n - 1 - i)) :: ll

  }

  var ans = List(rr(1), ll(1)).max

  rr = rr.reverse

  (1 until n - 1).foreach { i =>
    ans = max(ans, gcd(rr(i - 1), ll(i + 1)))
  }

  println(ans)
}


object Main extends App {

  import scala.math.max

  val n = scala.io.StdIn.readLine.toInt
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  def gcd(x: Int, y: Int): Int = {
    if (y == 0) {
      x
    } else
      gcd(y, x % y)
  }

  var rr = new Array[Int](n)
  var ll = new Array[Int](n)
  rr(0) = a.head
  ll(n - 1) = a.last
  (1 until n).foreach { i =>
    rr(i) = gcd(rr.head, a(i))

    ll(n - 1 - i) = gcd(ll.head, a(n - 1 - i))

  }
  var ans = List(rr(1), ll(1)).max

  rr = rr.reverse

  (1 until n - 1).foreach { i =>
    ans = max(ans, gcd(rr(i - 1), ll(i + 1)))
  }

  println(ans)
}


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  def gcd(x: Int, y: Int): Int = {
    if (y == 0) {
      x
    } else
      gcd(y, x % y)
  }

  var rr = List(a(0))
  var ll = List(a.last)
  (1 until n).foreach { i =>
    rr = gcd(rr(i - 1), a(i)) :: rr

    ll = gcd(ll.head, a(n - 1 - i)) :: ll

  }
  rr = rr.reverse

  var ans = List(rr(rr.length - 2), ll(1)).max
  (1 until n - 1).foreach { i =>
    ans = List(ans, gcd(rr(i - 1), ll(i + 1))).max
  }
  println(ans)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    sc.nextLine()

    val numbers: List[Int] = sc.nextLine().split(" ").map(_.toInt).toList
    if (numbers.distinct.length == 1) {
      println(numbers.head)
    } else {
      val left: List[Int] = numbers.scanLeft(numbers.head)((prev, post) => gcd(prev, post)).drop(1)
      val right: List[Int] = numbers.scanRight(numbers.last)((prev, post) => gcd(prev, post)).dropRight(1)
      val ans = numbers.zipWithIndex.map {
        item =>
          if (item._2 == 0) right(1)
          else if (item._2 == numbers.length - 1) left(left.length - 2)
          else {
            gcd(left(item._2 - 1), right(item._2 + 1))
          }
      }.max

      println(ans)
    }

  }

  def gcd(x: Int, y: Int): Int = {
    if (y == 0) x
    else gcd(y, x % y)
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    sc.nextLine()

    val numbers: List[Int] = sc.nextLine().split(" ").map(_.toInt).toList
    if (numbers.distinct.length == 1) {
      println(numbers.head)
    } else {
      val left: List[Int] = numbers.scanLeft(numbers.head)((prev, post) => gcd(prev, post)).drop(1)
      val right: List[Int] = numbers.scanRight(numbers.last)((prev, post) => gcd(prev, post)).dropRight(1)
      val ans = numbers.zipWithIndex.map {
        item =>
          if (item._2 == 0) right.head
          else if (item._2 == numbers.length - 1) left.last
          else {
            gcd(left(item._2 - 1), right(item._2 + 1))
          }
      }.max

      println(ans)
    }

  }

  def gcd(x: Int, y: Int): Int = {
    if (y == 0) x
    else gcd(y, x % y)
  }
}


import java.util.Scanner

import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val N  = StdIn.readLine().toInt
    val As  = StdIn.readLine().split(" ").map(_.toInt)

    val a = As.indices.map { i =>
      val b = new ArrayBuffer[Int]
      As.map{ c =>
        b += c
      }
      b.remove(i)
      b
    }
    val ret = a.map(_.reduce(gcd)).max
    println(s"$ret")
  }

  @tailrec
  def gcd(x: Int, y: Int): Int = {
    if(y == 0) x
    else gcd(y, (x % y))
  }
}


import java.util.Scanner

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

  val n = sc.nextInt

  val al = List.fill(n)(sc.nextInt)

  val res =
    (0 until n).foldLeft(1){(max, i) =>
      val t2 = al.zipWithIndex.filter(_._2 != i).map(_._1)

      val temp = t2.tail.foldLeft(t2.head)(gcd(_,_))

      Math.max(max, temp)
    }
  println(res)

  def gcd(a: Int, b: Int): Int ={
    (a,b) match{
      case (x,y) if y == 0 => x
      case (x,y) if x < y  => gcd(y, x)
      case (x,y)           => gcd(y, x % y)
    }
  }

}


import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val As = List.fill(N)(sc.nextInt())

    val left = As.scanLeft(0) {(pre, x) => gcd(pre, x)}
    val right = As.scanRight(0) {(pre, x) => gcd(pre, x)}

    val ret = for(i <- 0 to As.size) yield {
      gcd(left(i), right(i + 1))
    }
    println(ret.max)
  }

  @tailrec
  def gcd(x: Int, y: Int): Int = {
    if(y == 0) x
    else gcd(y, (x % y))
  }
}


import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val As = List.fill(N)(sc.nextInt())

    val left = As.scanLeft(0) {(pre, x) => gcd(pre, x)}
    val right = As.scanRight(0) {(pre, x) => gcd(pre, x)}

    val ret = for(i <- 0 to As.size) yield {
      gcd(left(i), right(i + 1))
    }
    println(ret)
  }

  @tailrec
  def gcd(x: Int, y: Int): Int = {
    if(y == 0) x
    else gcd(y, (x % y))
  }
}


import scala.io.StdIn.readLine

object Main{
  def main(args: Array[String]): Unit ={
    val n : Int = readLine().toInt
    val A : Array[Int] = readLine().split(' ').map(_.toInt)
    println(new Solve(n, A).solve())
  }
}

class Solve(val n : Int, val A : Array[Int]){
  def gcd(a : Int, b : Int): Int = if(b == 0) a else gcd(b, a % b)
  val Front : Array[Int] = {
    val k : Array[Int] = Array.fill(n)(0)
    for(i <- 1 until n) k(i) = gcd(k(i-1), A(i-1))
    k
  }
  val Back : Array[Int] = {
    val k : Array[Int] = Array.fill(n)(0)
    for(i <- n-2 to 0 by -1) k(i) = gcd(A(i+1), k(i+1))
    k
  }
  def solve(idx : Int = 0, res : Int = -1) : Int = {
    if(idx == n) res
    else{
      val USA : Int = gcd(Front(idx), Back(idx))
      solve(idx + 1, if(USA > res) USA else res)
    }
  }
}


import scala.io.StdIn

object Main extends App {
  val n  = StdIn.readLine().toInt
  val a  = StdIn.readLine().split(" ").map(_.toInt)

  def solve(a: Array[Int]): Int = {

    val b = a.scanLeft(0) {(acc, x) => gcd(acc, x)}
    val c = a.scanRight(0) {(acc, x) => gcd(acc, x)}

    val d = for (x <- 0 to a.length -1) yield {
      gcd(b(x), c(x + 1))
    }
    d.max
  }

  def gcd(x: Int, y: Int) :Int = {
    if (y == 0 ) x
    else gcd(y, (x % y))
  }

  println(solve(a))

}


import scala.io.StdIn

object Main extends App {
  val n  = StdIn.readLine().toInt
  val a  = StdIn.readLine().split(" ").map(_.toInt)

  def solve(a: Array[Int]): Int = {

    if (a.length == 2) {
      a.max
    } else {
      val c = for (x <- 0 to a.length - 1) yield {

        gcd(a.slice(0, x).foldLeft(0) { (acc, x) => gcd(acc, x)},
          a.slice(x + 1, a.length).foldLeft(0) { (acc, x) => gcd(acc, x)})

      }
      c.max
    }
  }

  def gcd(x: Int, y: Int) :Int = {
    if (y == 0 ) x
    else gcd(y, (x % y))
  }

  println(solve(a))

}


object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toSeq
    println(solve(lines))
  }

  def solve(lines: Seq[String]): String = {
    val n = lines.head.toInt
    val values = lines(1).split(" ").take(n).map(_.toLong).toSeq

    if (values.min == values.max) {
      values.max.toString
    } else {
      var result = 0L
      for (i <- values.indices) {
        val vs =
          if (i == 0) {
            values.slice(1, values.size)
          } else if (i == values.size - 1) {
            values.slice(0, values.size - 1)
          } else {
            values.slice(0, i) ++: values.slice(i + 1, values.size)
          }
        if (vs.size > 1) {
          for (j <- 1 until vs.size) {
            val g = gcd(vs(j), vs(j - 1))
            if (g > result) result = g
          }
        } else {
          val g = gcd(vs(0), 0)
          if (g > result) result = g
        }
      }
      result.toString
    }
  }

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


object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toSeq
    println(solve(lines))
  }

  def solve(lines: Seq[String]): String = {
    val n = lines.head.toInt
    val values = lines(1).split(" ").take(n).map(_.toLong).toSeq

    if (values.min == values.max) {
      values.max.toString
    } else {
      var result = 0L
      for (i <- values.indices) {
        val vs =
          if (i == 0) {
            values.slice(1, values.size)
          } else if (i == values.size - 1) {
            values.slice(0, values.size - 1)
          } else {
            values.slice(0, i) ++: values.slice(i + 1, values.size)
          }
        for (j <- 1 until vs.size) {
          val g = gcd(vs(j), vs(j - 1))
          if (g > result) result = g
        }
      }
      result.toString
    }
  }

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


import java.util.Scanner

import scala.collection.mutable

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val A = 1 to N map (_ => sc.nextInt)

    val ans = Math.max(scan(A(0), A.drop(1)), scan(A(1), A.take(1) ++ A.drop(2)))
    println(ans)

  }

  def scan(t: Int, A: Seq[Int]): Int = {

    val mx = Math.sqrt(t).toInt + 1
    val candidates = (1 to mx).filter(t % _ == 0).flatMap(x => Seq(x, t/x)).distinct

    val map: mutable.Map[Int, Int] = mutable.Map(candidates.map(_ -> 0): _*)
    A.foreach { a =>
      candidates.foreach { c =>
        {
          val d = if (a % c != 0) 1 else 0
          map.put(c, map.get(c).get + d)
        }
      }
    }
    map.filter(_._2 <= 1).keySet.max
  }
}


import java.util.Scanner

import scala.collection.mutable

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val A = 1 to N map (_ => sc.nextInt)

    val ans = Math.max(scan(A(0), A.drop(1)), scan(A(1), A.take(1) ++ A.drop(2)))
    println(ans)

  }

  def scan(t: Int, A: Seq[Int]): Int = {

    val mx = Math.sqrt(t).toInt + 1
    val candidates = (1 to mx).filter(t % _ == 0).flatMap(x => Seq(x, (t/x)))

    val map: mutable.Map[Int, Int] = mutable.Map(candidates.map(_ -> 0): _*)
    map.put(1, 0)
    A.foreach { a =>
      candidates.foreach { c =>
        {
          val d = if (a % c != 0) 1 else 0
          map.put(c, map.get(c).get + d)
        }
      }
    }
    val filtered = map.filter(_._2 <= 1)
    (map.filter(_._2 <= 1).keySet).max
  }
}


import java.util.Scanner

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

object Main {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val As = List.fill(N)(sc.nextInt())

    val a = As.indices.map { i =>
      val b = new ArrayBuffer[Int]
      As.map{ c =>
        b += c
      }
      b.remove(i)
      b
    }
    val ret = a.map(_.reduce(gcd)).max
    println(s"$ret")
  }

  @tailrec
  def gcd(x: Int, y: Int): Int = {
    if(y == 0) x
    else gcd(y, (x % y))
  }
}


import scala.util.control.Breaks

object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toSeq
    println(solve(lines))
  }

  def solve(lines: Seq[String]): String = {
    val n = lines.head.toInt
    val values = lines(1).split(" ").take(n).map(_.toLong)

    if (values.min == values.max) {
      values.max.toString
    } else {
      var divisersList = Vector[Vector[Long]]()
      for (i <- values.indices) {
        val d = divisors(values(i))
        divisersList = d +: divisersList
      }
      val reversed = divisersList.flatten.distinct.sorted.reverse
      var result = 0L
      val b = new Breaks
      b.breakable {
        reversed.foreach { v =>
          if (divisersList.count(_.contains(v)) >= n - 1) {
            result = v
            b.break()
          }
        }
      }
      result.toString
    }
  }

  def divisors(n: Long): Vector[Long] =
    (for (i <- 1L to n if n % i == 0) yield i).toVector
}


object Main extends App {
  val n = scala.io.StdIn.readInt()
  var aInput = scala.io.StdIn.readLine()
  val aArray =  aInput.split(" ").map(_.toInt).toVector
  var max = 0
  def getGcd(aInput: Int, bInput: Int): Int = {
    var tmp = 0
    var aInit = 0
    var bInit = 0
    if(aInput > bInput) {
      aInit = bInput
      bInit = aInput
    } else {
      aInit = aInput
      bInit = bInput
    }
    var a = aInit
    var b = bInit
    // println(s"------------${aInput}:${bInput}----------------")
    while ( {
      tmp = a % b
      // println(tmp)
      tmp != 0
    }) {
      a = b
      b = tmp
    }
    if(b == bInit) {
      1
    } else {
      b
    }
  }
  if(n == 2) {
    max = if (aArray(0) > aArray(1)) aArray(0) else aArray(1)
  } else {
    val lastIndex = aArray.length - 1
    // 最初を起点にした最大公約数リスト
    val list1 = aArray.tail.map(a => getGcd(aArray(0), a)).sorted
    // 最後を起点とした最大公約数リスト
    val list2 = aArray.init.map(a => getGcd(aArray(lastIndex), a)).sorted
    // println(list1)
    // println(list2)
    // 最小から二つ目の大きい方
    var maxList = Vector.empty[Int]
    if (list1(1) > list2(1)) {
      maxList = list1.tail
    } else {
      maxList = list2.tail
    }
    if(maxList.length > 1) {
      max = getGcd(maxList(0), maxList(1))
    } else {
      max = maxList(0)
    }

  }
  print(max)
}


import scala.annotation.tailrec
import scala.collection.mutable.Map

object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App {

  var cache = Map.empty[(Int,Int),Int]

  def gcd(a:Int,b:Int):Int = {
    if (b == 0) {
      a
    } else if (cache.isDefinedAt(a,b)){
      cache(a,b)
    }else {
      val result = gcd (b,a%b)
      cache.put((b,a),result)
      result
    }
  }

  @tailrec
  def rec(ar:Array[Int]): Int = {
    if (ar.length == 1) {
      ar(0)
    } else {
      rec(ar.tail.map(x=>gcd(x,ar(0))).sorted)
    }
  }

  val n = Scanner.nextInt()
  val a = Array.fill(n)(Scanner.nextInt())
  val sortedA = a.sorted
  val candidate1 = rec(sortedA.tail)
  val candidate2 = rec(sortedA.zipWithIndex.filter(_._2 != 1).map(_._1))

  println(Array(candidate1,candidate2).max)
}


object Main {

  @scala.annotation.tailrec
  private def gcd(a: Int, b: Int): Int = {
    val r = a % b
    if (r == 0) b
    else gcd(b, r)
  }

  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readLine().toInt
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val m = Array.fill(n, n)(Int.MinValue)

    for {
      i <- 0 until n
      j <- 0 until n
      if i == j
    } m(i)(i) = a(i)

    (0 until n - 1).foreach { i =>
      ((i + 1) until n).foreach { j =>
        m(i)(j) = gcd(m(i)(j-1), a(j))
      }
    }

    val res = (0 until n).map { i =>
      if (i == 0) {
        m(1)(n-1)
      } else if (i == n - 1) {
        m(0)(n-2)
      } else {
        gcd(m(0)(i-1), m(i+1)(n-1))
      }
    }. max

    println(res)
  }

}


object Main extends App {
  var N = readInt
  var get = readLine.split(" ")
  var max = 0
  var min = 1000000001
  var check = 0
  for(i <- 0 until N){
    max = math.max(max,get(i).toInt)
    min = math.min(min,get(i).toInt)
  }
  for(i <- 1 until min){
    if(max % i == 0 && min % i == 0)
    check = i
  }
  println(check)
}


object Main extends App {
  var N = readInt
  var get = readLine.split(" ")
  var max = 0
  var min = 1000000001
  var check = 0
  for(i <- 0 until N){
    max = math.max(max,get(i).toInt)
    min = math.min(min,get(i).toInt)
  }
  for(i <- 1 until max){
    if(max % i == 0 && min % i == 0)
    check = i
  }
  println(check)
}


import scala.annotation.tailrec

object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App {

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

  @tailrec
  def rec(ar:Array[Int]): Int = {
    if (ar.length == 1) {
      ar(0)
    } else {
      rec(ar.tail.map(x=>gcd(x,ar(0))).sorted)
    }
  }

  val n = Scanner.nextInt()
  val a = Array.fill(n)(Scanner.nextInt())
  val sortedA = a.sorted
  val candidate1 = rec(sortedA.tail)
  val candidate2 = rec(sortedA.zipWithIndex.filter(_._2 != 1).map(_._1))

  println(Array(candidate1,candidate2).max)
}


import scala.annotation.tailrec

object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App {

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

  @tailrec
  def rec(ar:Array[Int]): Int = {
    if (ar.length == 1) {
      ar(0)
    } else {
      rec(ar.tail.map(x=>gcd(x,ar(0))).sorted)
    }
  }

  val n = Scanner.nextInt()
  val a = Array.fill(n)(Scanner.nextInt())
  val ai = a.sorted.zipWithIndex

  val result = (0 until n).map{ i=> {
    rec(ai.filter(_._2 != i).map(_._1))
  }}.max

  println(result)
}


import scala.annotation.tailrec

object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App {

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

  val n = Scanner.nextInt()
  val a = Array.fill(n)(Scanner.nextInt())
  val ai = a.zipWithIndex

  val result = (0 until n).map{ i=> {
    ai.filter(_._2 != i).foldLeft(0)((x,y)=>gcd(x,y._1))
  }}.max

  println(result)
}


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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val L, R = Array.ofDim[Int](N)
    L(0) = A(0)
    R(N - 1) = A(N - 1)
    REP(N - 1, 1) { i =>
      L(i) = gcd(L(i - 1), A(i))
    }
    REP_r(N - 1) { i =>
      R(i) = gcd(R(i + 1), A(i))
    }

    debug(L)
    debug(R)

    var g = max(L(N - 2), R(1))
    TO(1, N - 2) { i =>
      g = max(g, gcd(L(i - 1), R(i + 1)))
    }

    out.println(g)
  }

  type A = Int

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

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

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

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

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

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

  def debugDim(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m.length) { i =>
      debug(m(i))
    }
  }

  def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }

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

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

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

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

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

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

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

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


Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4

Sample Output 3

563038556


import java.util.Scanner

//ResidueRingを改良(値クラスへ)
object Main {

  /*
  case class ResidueRing(representative: Long) extends AnyVal {
    def +(that: ResidueRing): ResidueRing = ResidueRing((this.representative + that.representative) % ResidueRing.mod)

    def -(that: ResidueRing): ResidueRing = ResidueRing((this.representative - that.representative + ResidueRing.mod) % ResidueRing.mod)

    def *(that: ResidueRing): ResidueRing = ResidueRing((this.representative * that.representative) % ResidueRing.mod)

    def unary_- : ResidueRing = ResidueRing((-this.representative + ResidueRing.mod) % ResidueRing.mod)
  }

  object ResidueRing {
    val mod: Long = 998244353

    val _0: ResidueRing = ResidueRing(0)
    val _1: ResidueRing = ResidueRing(1)
  }
  */
  case class ResidueRing(private val input: Long) {
    val representative: Long = ((input % ResidueRing.mod) + ResidueRing.mod) % ResidueRing.mod

    def +(that: ResidueRing): ResidueRing = ResidueRing(this.representative + that.representative)

    def -(that: ResidueRing): ResidueRing = ResidueRing(this.representative - that.representative)

    def *(that: ResidueRing): ResidueRing = ResidueRing(this.representative * that.representative)

    def unary_- : ResidueRing = ResidueRing(-this.representative)

  }

  object ResidueRing {
    val mod: Long = 998244353

    val _0: ResidueRing = ResidueRing(0)
    val _1: ResidueRing = ResidueRing(1)
  }

  def read() = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = for (_ <- 0 until n) yield sc.nextInt()
    (n, a)
  }

  /*
  N<-[3,300]
  [a_i<-[1,300] | i<-[0,N)]
  ---
  S = sum [a_i | i<-[0,N)]
  W = {(x,y,z)<-[0,S]^3 | x+y+z = S}
  C={r,g,b}
  phi: [[0,N)->C]->W,
  phi(f) = (x,y,z) where
    x = sum [a_i | i<-[0,N), f(i)==r]
    y = sum [a_i | i<-[0,N), f(i)==g]
    z = sum [a_i | i<-[0,N), f(i)==b]
  Q = {(x,y,z)<-W | x<y+z, y<z+x, z<x+y}
  K = phi^-1[Q]
  find #K
  T=Q^c
  T1 = {(x,y,z)<-W | x>=y+z} = {(x,y,z)<-W | x>=S/2}
  T2 = {(x,y,z)<-W | x>=y+z} = {(x,y,z)<-W | y>=S/2}
  T3 = {(x,y,z)<-W | x>=y+z} = {(x,y,z)<-W | z>=S/2}
  T12 = T1/\T2 = {(x,y,z)<-W | x=y, z=0} = {(x,y,z)<-W | x=y=S/2}
  T23 = T2/\T3 = {(x,y,z)<-W | y=z, x=0} = {(x,y,z)<-W | y=z=S/2}
  T31 = T3/\T1 = {(x,y,z)<-W | z=x, y=0} = {(x,y,z)<-W | z=x=S/2}
  T123 = T1/\T2/\T3 = {}
  (if S/2 is not a integer, T12=T23=T31={})
  #K = #[[0,N)->C] - #phi^-1[Q^c]
     = 3^N - #phi^-1[Q^c]
  #phi^-1[Q^c]
   = #phi^-1[T]
    = #phi^-1[T1] + #phi^-1[T2] + #phi^-1[T3] - #phi^-1[T12] - #phi^-1[T23] - #phi^-1[T31]
    = 3*#phi^-1[T1] - 3*#phi^-1[T23]

  dp1: [0,N]*[0,S]->\N
  dp1(k,x) = #{f:[0,k)->C | sum [a_i | i<-[0,k), f(i)==r] = x}
  dp1(0,0) = 1, dp1(0,x) = 0 (x<-(0,S] )
  dp1(k,x) = 2*dp1(k-1,x)+(if(x-a_{k-1}>=0) dp1(k-1, x-a_{k-1} else 0)
    (k>=1)
  #phi^-1[T1] = sum [dp1(N,x) | x<-[S/2,S]]

  [S_k = sum [a_i | i<-[0,k)] | k<-[0,N]]
    (satisfy: S_N = S)
  dp23: [0,N]*[0,S/2]->\N
  dp23(k,y) = #{f:[0,k)->C | sum [a_i | i<-[0,k), f(i)==g] = y, sum [a_i | i<-[0,k), f(i)==b] = (S_k - y)}
  dp23(0,0) = 1, dp23(0,y) = 0 (y<-(0,S/2])
  dp23(k,y) = (if(y-a_{k-1}>=0) dp23(k-1, y-a_{k-1}) else 0) + dp23(k-1,y)
  #phi^-1[T23] = dp23(N, S/2)
  */

  // ナイーブ実装
  def pow(base: ResidueRing, n: Int): ResidueRing = List.fill(n)(base).foldLeft(ResidueRing(1))(_ * _)

  def solve(n: Int, a: IndexedSeq[Int]): Long = {
    val numAll = pow(ResidueRing(3), n)
    val numNotTriangle = {
      val s = a.sum
      val phiInvT1 = {
        var dp1: Array[ResidueRing] = Array.fill(s + 1)(ResidueRing(0))
        dp1(0) = ResidueRing(1)
        for (k <- 1 to n) {
          var dp1next = Array.fill(s + 1)(ResidueRing(0))
          for (x <- 0 to s) {
            dp1next(x) = ResidueRing(2) * dp1(x) + (if (x - a(k - 1) >= 0) dp1(x - a(k - 1)) else ResidueRing(0))
          }
          dp1 = dp1next
        }
        val range = if (s % 2 == 0) s / 2 to s else s / 2 + 1 to s
        range.map(x => dp1(x)).foldLeft(ResidueRing(0))(_ + _)
      }
      val phiInvT23 = {
        if (s % 2 != 0) ResidueRing(0)
        else {
          var dp23: Array[ResidueRing] = Array.fill(s / 2 + 1)(ResidueRing(0))
          dp23(0) = ResidueRing(1)
          for (k <- 1 to n) {
            val dp23next = Array.fill(s / 2 + 1)(ResidueRing(0))
            for (y <- 0 to s / 2) {
              dp23next(y) = (if (y - a(k - 1) >= 0) dp23(y - a(k - 1)) else ResidueRing(0)) + dp23(y)
            }
            dp23 = dp23next
          }
          dp23(s / 2)
        }
      }
      ResidueRing(3) * phiInvT1 - ResidueRing(3) * phiInvT23
    }
    (numAll - numNotTriangle).representative
  }

  def main(args: Array[String]): Unit = {
    val (n, a) = read()
    println(solve(n, a))
  }

}


import java.util.Scanner

object Main {

  case class ResidueRing(private val input: Long) {
    val representative: Long = ((input % ResidueRing.mod) + ResidueRing.mod) % ResidueRing.mod

    def +(that: ResidueRing): ResidueRing = ResidueRing(this.representative + that.representative)

    def -(that: ResidueRing): ResidueRing = ResidueRing(this.representative - that.representative)

    def *(that: ResidueRing): ResidueRing = ResidueRing(this.representative * that.representative)

    def unary_- : ResidueRing = ResidueRing(-this.representative)

  }

  object ResidueRing {
    val mod: Long = 998244353

    val _0: ResidueRing = ResidueRing(0)
    val _1: ResidueRing = ResidueRing(1)
  }

  def read() = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = for (_ <- 0 until n) yield sc.nextInt()
    (n, a)
  }

  /*
  N<-[3,300]
  [a_i<-[1,300] | i<-[0,N)]
  ---
  S = sum [a_i | i<-[0,N)]
  W = {(x,y,z)<-[0,S]^3 | x+y+z = S}
  C={r,g,b}
  phi: [[0,N)->C]->W,
  phi(f) = (x,y,z) where
    x = sum [a_i | i<-[0,N), f(i)==r]
    y = sum [a_i | i<-[0,N), f(i)==g]
    z = sum [a_i | i<-[0,N), f(i)==b]
  Q = {(x,y,z)<-W | x<y+z, y<z+x, z<x+y}
  K = phi^-1[Q]
  find #K
  T=Q^c
  T1 = {(x,y,z)<-W | x>=y+z} = {(x,y,z)<-W | x>=S/2}
  T2 = {(x,y,z)<-W | x>=y+z} = {(x,y,z)<-W | y>=S/2}
  T3 = {(x,y,z)<-W | x>=y+z} = {(x,y,z)<-W | z>=S/2}
  T12 = T1/\T2 = {(x,y,z)<-W | x=y, z=0} = {(x,y,z)<-W | x=y=S/2}
  T23 = T2/\T3 = {(x,y,z)<-W | y=z, x=0} = {(x,y,z)<-W | y=z=S/2}
  T31 = T3/\T1 = {(x,y,z)<-W | z=x, y=0} = {(x,y,z)<-W | z=x=S/2}
  T123 = T1/\T2/\T3 = {}
  (if S/2 is not a integer, T12=T23=T31={})
  #K = #[[0,N)->C] - #phi^-1[Q^c]
     = 3^N - #phi^-1[Q^c]
  #phi^-1[Q^c]
   = #phi^-1[T]
    = #phi^-1[T1] + #phi^-1[T2] + #phi^-1[T3] - #phi^-1[T12] - #phi^-1[T23] - #phi^-1[T31]
    = 3*#phi^-1[T1] - 3*#phi^-1[T23]

  dp1: [0,N]*[0,S]->\N
  dp1(k,x) = #{f:[0,k)->C | sum [a_i | i<-[0,k), f(i)==r] = x}
  dp1(0,0) = 1, dp1(0,x) = 0 (x<-(0,S] )
  dp1(k,x) = 2*dp1(k-1,x)+(if(x-a_{k-1}>=0) dp1(k-1, x-a_{k-1} else 0)
    (k>=1)
  #phi^-1[T1] = sum [dp1(N,x) | x<-[S/2,S]]

  [S_k = sum [a_i | i<-[0,k)] | k<-[0,N]]
    (satisfy: S_N = S)
  dp23: [0,N]*[0,S/2]->\N
  dp23(k,y) = #{f:[0,k)->C | sum [a_i | i<-[0,k), f(i)==g] = y, sum [a_i | i<-[0,k), f(i)==b] = (S_k - y)}
  dp23(0,0) = 1, dp23(0,y) = 0 (y<-(0,S/2])
  dp23(k,y) = (if(y-a_{k-1}>=0) dp23(k-1, y-a_{k-1}) else 0) + dp23(k-1,y)
  #phi^-1[T23] = dp23(N, S/2)
  */

  // ナイーブ実装
  def pow(base: ResidueRing, n: Int): ResidueRing = List.fill(n)(base).foldLeft(ResidueRing(1))(_ * _)

  def solve(n: Int, a: IndexedSeq[Int]): Long = {
    val numAll = pow(ResidueRing(3), n)
    val numNotTriangle = {
      val s = a.sum
      val phiInvT1 = {
        val dp1: Array[Array[ResidueRing]] = Array.fill(n + 1)(Array.fill(s + 1)(ResidueRing(0)))
        dp1(0)(0) = ResidueRing(1)
        for (k <- 1 to n; x <- 0 to s) {
          dp1(k)(x) = ResidueRing(2) * dp1(k - 1)(x) + (if (x - a(k - 1) >= 0) dp1(k - 1)(x - a(k - 1)) else ResidueRing(0))
        }
        val range = if (s % 2 == 0) s / 2 to s else s / 2 + 1 to s
        range.map(x => dp1(n)(x)).foldLeft(ResidueRing(0))(_ + _)
      }
      val phiInvT23 = {
        if (s % 2 != 0) ResidueRing(0)
        else {
          val dp23: Array[Array[ResidueRing]] = Array.fill(n + 1)(Array.fill(s / 2 + 1)(ResidueRing(0)))
          dp23(0)(0) = ResidueRing(1)
          for (k <- 1 to n; y <- 0 to s / 2) {
            dp23(k)(y) = (if (y - a(k - 1) >= 0) dp23(k - 1)(y - a(k - 1)) else ResidueRing(0)) + dp23(k - 1)(y)
          }
          dp23(n)(s / 2)
        }
      }
      ResidueRing(3) * phiInvT1 - ResidueRing(3) * phiInvT23
    }
    (numAll - numNotTriangle).representative
  }

  def main(args: Array[String]): Unit = {
    val (n, a) = read()
    println(solve(n, a))
  }

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val A, B, C = sc.nextInt()
  println((B / A).min(C))
}

Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


import scala.io.StdIn._

object Main extends App {

  val Array(a,b,c) = readLine().split(" ").map(_.toInt)

  def solve() = {
    if(b/a >= c) c
    else b/a
  }
  println(solve())

}


import io.StdIn.{readLine}
import math.min
object Main extends App{
  var Array(a,b,c) = readLine.split(" ").map(_.toInt)
  println(min(b/a,c))
}


import io.StdIn.{readLine}
import math.min
object Main extends App{
  var Array(a,b,c) = readLine.split(" ").map(_.toInt)
  println(min(a/b,c))
}


import java.util.Scanner

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

  val a = sc.nextInt                 // 入力Aを受け付けて、aに格納する
  val b = sc.nextInt                 // 入力Bを受け付けて、bに格納する
  val c = sc.nextInt                 // 入力Cを受け付けて、cに格納する

  val res = Math.max(b/a, c)         // B/A と C のうち、小さくない方 を計算する

  println(res)                       // 結果を出力する
}


import java.util.Scanner

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

  val a = sc.nextInt
  val b = sc.nextInt
  val c = sc.nextInt

  val res = Math.min(b/a, c)

  println(res)
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val (a, b, c) = (sc.nextInt(), sc.nextInt(), sc.nextInt())
  println(math.min(b / a, c))
}


object Main extends App {
  val Array(a, b, c) = io.StdIn.readLine.split(" ").map(_.toInt)
  println(math.min(b / a, c))
}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val A, B, C = sc.nextInt()

    println((B / A) min C)
  }

}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val A = Integer.parseInt(sc.next())
    val B = Integer.parseInt(sc.next())
    val C = Integer.parseInt(sc.next())

    println(Math.min(B / A, C))
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
//  val l = List.fill(5)(sc.nextInt)
  val a, b, c = sc.nextInt

  val ans = b / a
  println(if (c <= ans) c else ans)
}


import java.io.PrintWriter
import java.util

object Main {

  def main(args: Array[String]) {
    val stdin = scala.io.StdIn

    val printWriter = new PrintWriter(System.out)

    val a = stdin.readLine().split(" ").map(i => i.toInt)

    printWriter.println(Math.min(a(1) / a(0), a(2)))

    printWriter.close()
  }
}


object Main extends App {
    val abc = scala.io.StdIn.readLine()

    val a = abc.split(" ")(0).toInt
    val b = abc.split(" ")(1).toInt
    val c = abc.split(" ")(2).toInt

    println(List(b/a, c).min)
}


object Main extends App {
    val abc = scala.io.StdIn.readLine()

    abc.split(" ")
    abc.split(" ")(0)

    val a = abc.split(" ")(0).toInt
    val b = abc.split(" ")(1).toInt
    val c = abc.split(" ")(2).toInt

    println(List(b/a, c).min)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val Array(a, b, c) = sc.nextLine.split(" ").map(_.toInt)

    val maxNumber: Int = b / a
    if (maxNumber > c) {
      println(c)
    } else {
      println(maxNumber)
    }
  }
}


object Main extends App {
	val Array(a, b, c) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
 	println(math.min(b/a, c))
}


object Main extends App {
  val inputLine = io.StdIn.readLine()
  val arr = inputLine.split(" ")
  val intArr = arr.map(_.toInt)

  def waru(A: Int, B: Int, C: Int): Unit = {
    val Answer = B / A
    if (Answer >= C) {
      println(C)
    } else {
      println(Answer)
    }
  }

  waru(intArr(0), intArr(1), intArr(2))
}


object Main extends App {
  var get = readLine
  var a = get.split(" ")(0).toInt
  var b = get.split(" ")(1).toInt
  var c = get.split(" ")(2).toInt
  var sum = 0
  var loop = Math.max(a,b)
  var d = 0
  while(loop > 0 || sum != c) {
    if(a % loop == 0 && b % loop == 0){
      sum += 1
    }
    loop -= 1
  }
		println(loop)
}


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

  val Array(a, b, c) = readLine.trim.split(' ').map(_.toInt)
  println(
    math.min(b / a, c)
  )
}


object Main extends App {
  var get = readLine
  var a = get.split(" ")(0).toInt
  var b = get.split(" ")(1).toInt
  var c = get.split(" ")(2).toInt

  println(if(b / a < c) b / a else c)
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.map(_.split(' ').map(_.toInt).toIndexedSeq).head
  val A = ls(0)
  val B = ls(1)
  val C = ls(2)

  val ret = Math.min(C, B/A)
  println(ret)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val A,B,C = sc.nextInt()

    val sound = B/A
    if (sound > C) println(C) else println(sound)
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a, b, c = sc.nextInt
  val ans = math.min(math.floor(b / a), c)
  println(ans.toInt)

}


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

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

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

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

  def solve(): Unit = {
    val A, B, C = ni()
    val ans = min(C, B / A)
    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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


import io.StdIn._
import math._

object Main extends App {
  val n = readInt()
  val hs = readLine() split(' ') map(_.toLong)

  val dp = new Array[Long](n)
  dp(0) = 0
  dp(1) = abs(hs(0) - hs(1))

  for (i <- 2 until n) {
    dp(i) = min(abs(hs(i)-hs(i-1))+dp(i-1), abs(hs(i)-hs(i-2))+dp(i-2))
  }

  println(dp.last)
}

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


import io.StdIn._

object Main extends App {
  val n = readInt()
  val hs = readLine() split(' ') map(_.toLong)

  def abs(a: Long, b: Long): Long =
    (a-b).abs

  val dp = Array.fill[Long](n)(Long.MaxValue)
  dp(0) = 0
  dp(1) = abs(hs(0),hs(1))

  for (i <- 2 until n) {
    dp(i) = math.min(abs(hs(i),hs(i-1)+dp(i-1)), abs(hs(i),hs(i-2))+dp(i-2))
  }

  println(dp.last)
}


import java.util.Scanner

import scala.math._

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

  val dp = Array.fill(N)(Int.MaxValue)

  dp(0) = 0
  for (i <- 1 until N) {
    val dp1 = dp(i - 1) + abs(h(i) - h(i - 1))
    val dp2 = if (i != 1) dp(i - 2) + abs(h(i) - h(i - 2)) else Int.MaxValue
    dp(i) = min(dp1, dp2)
  }
  println(dp.last)
}


import scala.io.StdIn._
object Main extends App {
  val n = readInt
  val h = readLine.split(" ").map(_.toInt)

  val dp = Array.fill[Int](n)(Int.MaxValue)
  dp(0) = 0
  dp(1) = math.abs(h(1) - h(0))
  for (i <- 2 to n - 1) {
    val d1 = dp(i - 1) + math.abs(h(i - 1) - h(i))
    val d2 = dp(i - 2) + math.abs(h(i - 2) - h(i))
    dp(i) = math.min(d1, d2)
  }

  println(dp(n - 1))
}


object Main extends App {
  val n = io.StdIn.readInt()
  val h = io.StdIn.readLine().split(' ').map(_.toInt)
  val dp = Array.fill(n)(-1)
  for (i <- 0 until n) {
    if (i == 0) dp(i) = 0
    else {
      val x = {
        val tmp = dp(i-1) + Math.abs(h(i-1) - h(i))
        if (i == 1) tmp else tmp.min(dp(i-2) + Math.abs(h(i-2) - h(i)))
      }
      if (dp(i) == -1 || x < dp(i)) dp(i) = x
    }
  }
  println(dp(n-1))
}


object Main {
  def main(args: Array[String]): Unit = {
    solve
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val h = new Array[Int](n)
    for (i <- 0 until n) {
      h(i) = sc.nextInt
    }

    // hiまでにかかるコスト
    val dp = Array.fill[Int](n)(Int.MaxValue)
    dp(0) = 0
    dp(1) = math.abs(h(1) - h(0))
    for (i <- 2 until n) {
      dp(i) = math.min(math.abs(h(i - 2) - h(i)) + dp(i - 2), math.abs(h(i - 1) - h(i)) + dp(i - 1))
    }
    println(dp(n - 1))
  }
}


object Main extends App {
  import scala.math._

  val n = readLong
  val h = readLine.split(" ").map{_.toLong}.toArray

  val dp = Array.fill[Long](n.toInt)(Long.MaxValue)
  dp(0) = 0
  dp(1) = abs(h(1) - h(0))

  for (i <- 2 until n.toInt) {
    dp(i) = min(dp(i-1)+abs(h(i)-h(i-1)),dp(i-2)+abs(h(i)-h(i-2)))
  }

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


object Main extends App {
  import scala.math._

  val n = readLong
  val h = readLine.split(" ").map{_.toLong}.toArray

  val dp = Array.fill[Long](n.toInt)(Long.MaxValue)
  dp(0) = 0
  dp(1) = abs(h(1) - h(0))

  for (i <- 2 until n.toInt) {
    dp(i) = min(min(dp(i),dp(i-1)+abs(h(i)-h(i-1))),dp(i-2)+abs(h(i)-h(i-2)))
  }

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


import scala.collection.mutable.ArrayBuffer

/**
  * created by naumov on 12/14/19
  */
object Main extends App {

  def calculate(k: Int, h: ArrayBuffer[Int], res: ArrayBuffer[Int]): Int = {
    if (0 == k)
      return 0

    if (-1 == res(k)) {
      res(k) = calculate(k - 1, h, res) + Math.abs(h(k) - h(k - 1))
      //println(s"temp res: ${res(k)}")
      if (k >= 2) {
        res(k) = Math.min(res(k), calculate(k - 2, h, res) + Math.abs(h(k) - h(k - 2)))
      }
    }

    res(k)
  }

  val scanner = new java.util.Scanner(System.in)
  val n = scanner.nextInt()

  var h = new scala.collection.mutable.ArrayBuffer[Int](n)
  for (k <- 0 until n) {
    h.append(scanner.nextInt())
  }

  var res = collection.mutable.ArrayBuffer.fill(n)(-1)

  println(calculate(n - 1, h, res))

}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val N = sc.nextInt()
    val H = Array.fill(N)(sc.nextInt())
    val dp = new Array[Int](N)

    dp(0) = 0
    var i = 1
    while (i < N) {
      if (i == 1)
        dp(i) = dp(i-1) + Math.abs(H(i-1) - H(i))
      else
        dp(i) =
          (dp(i-1) + Math.abs(H(i-1) - H(i))) min
            (dp(i-2) + Math.abs(H(i-2) - H(i)))
      i += 1
    }
    println(dp(N-1))
  }

}


import scala.io.StdIn
import scala.math._

object Main {

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine.toInt
    val hs = StdIn.readLine.split(" ").map(_.toInt)

    val rec = new Array[Int](n)
    rec(0) = 0
    rec(1) = abs(hs(1) - hs(0))
    for (i <- 2 until n) {
      rec(i) = min(rec(i - 1) + abs(hs(i) - hs(i - 1)), rec(i - 2) + abs(hs(i) - hs(i - 2)))
    }

    println(rec(n - 1))

  }
}


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

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

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {

  def solve(sc: => Scanner): Unit = {
    val A = Array.fill(sc.nextInt())(sc.nextLong())
    val B = Array.fill(A.length)(Long.MaxValue)
    B(0) = 0
    A.indices.foreach(i => {
      if (i - 2 >= 0) {
        B(i) = math.min(B(i), math.abs(A(i) - A(i - 2)) + B(i - 2))
      }
      if (i - 1 >= 0) {
        B(i) = math.min(B(i), math.abs(A(i) - A(i - 1)) + B(i - 1))
      }
    })
    println(B.last)
  }

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def calc(N: Long, R: Long, M: Long): Double = {
    math.sqrt(R * R - (R * 2 * ((M * 1.0 / N) - 0.5)) * (R * 2 * ((M * 1.0 / N) - 0.5))) * 2
  }

  def recursive(N1: Long, N2: Long, M1: Long, M2: Long): Long = {
    println(N1, N2, M1, M2)
    if (N1 + N2 == 0 || M1 + M2 == 0) -1
    else recursive(math.max(0, M1 - math.max(0, N1 + N2 - M2) / 2), math.max(0, M2 - N1 - N2) + math.max(0, N1 + N2 - M2) % 2, N1, N2) + 1
  }

  def check(s: String): Boolean = {
    if (s == "0") true
    else s(0) != '0' && 0 <= s.toInt && s.toInt <= 255
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    solve(sc)
  }
}

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  val codeTable = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}


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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val H = na(N)
    val cost = Array.fill[Int](N)(1e9.toInt + 10)
    cost(0) = 0
    REP(N) { i =>
      if (i + 1 < N) cost(i + 1) = min(cost(i + 1),  cost(i) + abs(H(i) - H(i + 1)))
      if (i + 2 < N) cost(i + 2) = min(cost(i + 2),  cost(i) + abs(H(i) - H(i + 2)))
    }
    out.println(cost(N - 1))
  }

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

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

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

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

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

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


object Main extends App {

  import scala.io.StdIn._

  val n = readLine.trim.toInt
  val h = readLine.trim.split(' ').map(_.toInt)
  val memo = Array.tabulate(n){_ ⇒ None: Option[Int]}.also{arr ⇒ arr(n - 1) = Some(0)}
  for (i ← (0 until n by 100).reverse){
    minCost(h, memo, i)
  }
  println(minCost(h, memo, 0))
  def minCost(heights: Array[Int], memo: Array[Option[Int]], current: Int = 0): Int = {
    if (current == heights.length) 0
    else {
      memo(current) match {
        case Some(r) ⇒ r
        case None ⇒
          (current + 1 to current + 2).filter(p ⇒ heights.indices.contains(p)).map(p ⇒ minCost(heights, memo, p) + math.abs(heights(p) - heights(current))).min.also{min ⇒ memo(current) = Some(min)}
      }
    }
  }
  implicit class Extend[T](value: T){
    def also(func: T ⇒ Unit): T = {func(value); value}
    def let[A](func: T ⇒ A): A = func(value)
  }
}


import io.StdIn._
import math._

object Main extends App {
  val Array(n, k) = readLine() split(' ') map(_.toInt)
  val hs = readLine() split(' ') map(_.toInt)

  val dp = new Array[Long](n)
  dp(0) = 0

  for (i <- 1 until min(n,k)) {
    dp(i) = (1 to i).map(j => dp(i-j)+abs(hs(i)-hs(i-j))).min
  }

  if (k <= n)
  for (i <- k until n) {
    dp(i) = (1 to k).map(j => dp(i-j)+abs(hs(i)-hs(i-j))).min
  }

  println(dp.last)
}

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


import scala.io.StdIn._
object Main extends App {
  val Array(n, k) = readLine.split(" ").map(_.toInt)
  val h = readLine.split(" ").map(_.toInt)

  val dp = Array.fill(n)(Int.MaxValue)
  dp(0) = 0
  for (i <- 0 until n; j <- 1 to k if (i + j) < n) {
    dp(i + j) = math.min(dp(i + j), dp(i) + math.abs(h(i) - h(i + j)))
  }
  println(dp(n - 1))
}


object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  val h = io.StdIn.readLine().split(' ').map(_.toInt)
  val dp = Array.fill(n)(-1)
  for (i <- 0 until n) {
    if (i == 0) dp(i) = 0
    else {
      val cost = ((if (k <= i) i-k else 0) until i).map(j => dp(j) + Math.abs(h(i) - h(j))).min
      dp(i) = cost
    }
  }
  println(dp(n-1))
}


object Main {
  def main(args: Array[String]): Unit = {
    solve
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, k = sc.nextInt
    val h = new Array[Int](n)
    for (i <- 0 until n) {
      h(i) = sc.nextInt
    }

    // hiまでにかかるコスト
    val dp = Array.fill[Int](n)(Int.MaxValue)
    dp(0) = 0
    for (i <- 0 until n) {
      for (j <- 1 to k) {
        if (i + j < n) {
          dp(i + j) = math.min(dp(i + j), dp(i) + (h(i) - h(i + j)).abs)
        }
      }
    }
    println(dp(n - 1))
  }
}


object Main{
  def main(args: Array[String]) : Unit = {
    System.err.println("ok")
    val sc = new java.util.Scanner(System.in)
    val n,k = sc.nextInt
    val h : Array[Int] = 0 +: (1 to n).toArray.map{_ => sc.nextInt }

    val dp = new Array[Int](n + 1)
    dp(n) = 0
    dp(n-1) = (h(n-1) - h(n)).abs
    (n-2 to 1 by -1).foreach{ x =>
      dp(x) = (1 to k).map { jump =>
        if(x + jump > n) {
          10000000
        } else {
          (h(x) - h(x + jump)).abs + dp(x+jump)
        }
      }.min
    }
    println(dp(1))
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val N, K = sc.nextInt()
    val H = Array.fill(N)(sc.nextInt())
    val Inf = Long.MaxValue / 10
    val dp = Array.fill(N)(Inf)

    dp(0) = 0L
    var i = 0
    while (i < N) {
      var k = 1
      val Upper = N min (i + K + 1)
      while (i + k < Upper) {
        dp(i + k) =
          (dp(i) + Math.abs(H(i) - H(i + k))) min
            dp(i + k)
        k += 1
      }
      i += 1
    }
    println(dp(N-1))
  }

}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val N, K = sc.nextInt()
    val H = Array.fill(N)(sc.nextInt())
    val Inf = Int.MaxValue / 10
    val dp = Array.fill(N)(Inf)

    dp(0) = 0
    var i = 0
    while (i < N) {
      var k = 1
      val Upper = N min (i + K + 1)
      while (i + k < Upper) {
        dp(i + k) =
          (dp(i) + Math.abs(H(i) - H(i + k))) min
            dp(i + k)
        k += 1
      }
      i += 1
    }
    println(dp(N-1))
  }

}


import scala.io.StdIn.readLine

object Main{
  def main(args : Array[String]): Unit ={
    val Array(n, k) : Array[Int] = readLine().split(' ').map(_.toInt)
    val H : Array[Int] = readLine().split(' ').map(_.toInt)
    val smn = subMain(n, H, k)
    smn.calculate(n - 1)
    println(smn.DP(n - 1))
  }
}

case class subMain(n : Int, H : Array[Int], k : Int){
  val DP : Array[Int] = Array.fill(n)(Int.MaxValue)
  def CostOfIandJ(i : Int)(j : Int): Int = math.abs( H(i) - H(j) )
  def calculate(m : Int): Unit ={
    if(DP(m) != Int.MaxValue) return
    if(m == 0){
      DP(0) = 0
    }
    else{
      calculate(m - 1)
      def subCalculate(l : Int) = CostOfIandJ(m)(l)
      if(m < k){
        for(i <- 0 until m){
          val tmp = subCalculate(i) + DP(i)
          DP(m) = math.min( DP(m) , tmp )
        }
      }
      else{
        for(i <- m - k until m){
          val tmp = subCalculate(i) + DP(i)
          DP(m) = math.min( DP(m) , tmp )
        }
      }
    }
  }
}