object Main {

  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
  }

  def main(args: Array[String]): Unit = {
    val H, W = Scanner.nextInt()
    val S = Array.fill(H)(Scanner.next())
    val dp = Array.fill[Short](H, W, 2)(-1) // 未計算の場合-1, dp(i)(j)(0) 縦の数 dp(i)(j)(1)横の数
    var i = 0
    while (i < H) {
      var j = 0
      while (j < W) {
        if (S(i)(j) == '.') { // 障害物ではない場合
          if (dp(i)(j)(0) == -1) { // 縦方向未計算の場合のみ計算
            var di = 0
            while (i + di < H && S(i+di)(j) == '.') { // 障害物に当たるか壁に当たるかまで
              di += 1
            }
            var dii = 0
            val hoge = (di - 1).toShort
            while (dii < di) {
              dp(i+dii)(j)(0) = hoge
              dii += 1
            }
          }
          if (dp(i)(j)(1) == -1) { // 横方向未計算の場合のみ計算
            var dj = 0
            while (j + dj < W && S(i)(j+dj) == '.') { // 障害物に当たるか壁に当たるかまで
              dj += 1
            }
            var djj = 0
            val hoge = (dj - 1).toShort
            while (djj < dj) {
              dp(i)(j+djj)(1) = hoge
              djj += 1
            }
          }
        }
        j += 1
      }
      i += 1
    }

    var max = 0
    i = 0
    while (i < H) {
      var j = 0
      while (j < W) {
        if (S(i)(j) == '.') { // 障害物ではない場合
          max = Math.max(max, dp(i)(j)(0) + dp(i)(j)(1) + 1)
        }
        j += 1
      }
      i += 1
    }
    println(max)
  }

}

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


import scala.io.StdIn

object Main extends App {
  val Array(n, a, b, c, d) = StdIn.readLine().split(" ").map(_.toInt)
  val S  = StdIn.readLine()

  def solve(s : String, a: Int, b: Int, c: Int, d: Int ): String = {
    val s1 = s.slice(a, c)
    val s2 = s.slice(b, d)

    if (s1.contains("##"))
      return "No"

    if (s2.contains("##"))
      return "No"

    if (s(c -1) == '#' || s(d -1) == '#')
      return "No"

    if (s.length() == 4)
      return "Yes"

    if (d < c) {
      if (s(b) == '.') {
        if (a + 1 == b || s(b - 2) == '.') {
          return "Yes"
        }
      }
      if (! s1.contains("..."))
        return "No"
    }

    "Yes"
  }

  println(solve(S, a, b, c, d))
}

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

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes

Submitted source-code file size, in bytes.

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

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


import scala.io.StdIn

object Main extends App {
  val Array(n, a, b, c, d) = StdIn.readLine().split(" ").map(_.toInt)
  val S  = StdIn.readLine()

  def solve(s : String, a: Int, b: Int, c: Int, d: Int ): String = {
    val s1 = s.slice(a - 1, c)
    val s2 = s.slice(b - 1, d)

    if (s1.contains("##"))
      return "No"

    if (s2.contains("##"))
      return "No"

    if (d < c) {
      if (s(b) == '.') {
        if (a + 1 == b || s(b - 2) == '.') {
          return "Yes"
        }
      }
      if (! s1.contains("..."))
        return "No"
    }

    "Yes"
  }

  println(solve(S, a, b, c, d))
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.head.split(' ').map(_.toInt)
  val S = in.tail.head
  val N = ls(0)
  val A = ls(1)
  val B = ls(2)
  val C = ls(3)
  val D = ls(4)
  private def func(s:String, a:Int, b:Int):Boolean = {
    val sub = s.slice(a, b)
    sub.contains("##")
  }
  if(func(S, A, C) || func(S, B, D)) println("No")
  else if(D < C && !S.contains("...")) println("No")
  else println("Yes")
}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

case class Question(b: Int, l: Int, u: Int)
case class Entry(i: Int, v: Long)
case class Val(i: Int, v: Long)

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, X = ni()

    var sum = 0L

    val forX = Array.ofDim[Val](N)
    val questions = Array.ofDim[Question](N)

    REP(N) { i =>
      val b, l, u = ni()
      forX(i) = Val(i, l.toLong * b + (X - b).toLong * u)
      questions(i) = Question(b, l, u)
      sum += b.toLong * l
    }

    debug(s"sum:$sum")

    sort(forX, new Comparator[Val] {
      override def compare(o1: Val, o2: Val): Int = -java.lang.Long.compare(o1.v, o2.v)
    })

    val forXSum = Array.ofDim[Long](N + 1)
    REP(N) { i =>
      forXSum(i + 1) = forXSum(i) + forX(i).v
    }

    debug(forX.mkString(" "))
    debug(forXSum)

    def test(a: Long): Boolean = {
      val p = (a / X).toInt
      val cnt = a % X
      val needs = sum - forXSum(min(N, p))

      debug(s"a: $a p:$p cnt:$cnt needs:$needs")

      if (needs <= 0) true
      else if (cnt == 0) false
      else {
        var mx: Entry = null
        TO(p, N - 1) { ii =>
          val i = forX(ii).i
          val q = questions(i)
          val entry = if (needs <= q.b) {
            Entry(i, q.l)
          } else {
            val v = q.b.toLong * q.l + cnt.toLong * q.u
            Entry(i, v)
          }
          if (mx == null || entry.v > mx.v) mx = entry
        }

        val e = mx
        debug(s"cnt:$cnt")
        if (cnt <= questions(e.i).b) {
          needs <= questions(e.i).l.toLong * cnt
        } else {
          val cntL = questions(e.i).b
          val cntU = cnt - cntL
          debug(s"cntL:$cntL cntU:$cntU")
          needs <= questions(e.i).l.toLong * cntL + questions(e.i).u.toLong * cntU
        }
      }
    }

    val ans = findMin(test, 0L, sum)
    out.println(ans)
  }

  /**
    * 単調増加
    * (l, h] 方式
    */
  def findMin(f: Long => Boolean, min: Long, max: Long): Long = {
    var l = min - 1
    var h = max
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) h = x
      else l = x
    }
    h
  }
}

Score : 800 points

Problem Statement

Takahashi and Aoki will take N exams numbered 1 to N.
They have decided to compete in these exams.
The winner will be determined as follows:

For each exam i, Takahashi decides its importance c_i, which must be an integer between l_i and u_i (inclusive).

Let A be \sum_{i=1}^{N} c_i \times (Takahashi's score on Exam i), and B be \sum_{i=1}^{N} c_i \times (Aoki's score on Exam i). Takahashi wins if A \geq B, and Aoki wins if A < B.

Takahashi knows that Aoki will score b_i on Exam i, with his supernatural power.

Takahashi himself, on the other hand, will score 0 on all the exams without studying more. For each hour of study, he can increase his score on some exam by 1. (He can only study for an integer number of hours.)
However, he cannot score more than X on an exam, since the perfect score for all the exams is X.

Print the minimum number of study hours required for Takahashi to win.

Constraints

1 \leq N \leq 10^5

1 \leq X \leq 10^5

0 \leq b_i \leq X (1 \leq i \leq N)

1 \leq l_i \leq u_i \leq 10^5 (1 \leq i \leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
b_1 l_1 u_1
b_2 l_2 u_2
:
b_N l_N u_N

Output

Print the minimum number of study hours required for Takahashi to win.

Sample Input 1

2 100
85 2 3
60 1 1

Sample Output 1

115

One optimal strategy is as follows:

Choose c_1 = 3, c_2 = 1.

Study to score 100 on Exam 1 and 15 on Exam 2.

Then, A = 3 \times 100 + 1 \times 15 = 315, B = 3 \times 85 + 1 \times 60 = 315 and Takahashi will win.

Sample Input 2

2 100
85 2 3
60 10 10

Sample Output 2

77

Sample Input 3

1 100000
31415 2718 2818

Sample Output 3

31415

Sample Input 4

10 1000
451 4593 6263
324 310 6991
378 1431 7068
71 1757 9218
204 3676 4328
840 6221 9080
684 1545 8511
709 5467 8674
862 6504 9835
283 4965 9980

Sample Output 4

2540


//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 = {
    println(180 * (sc.nextLong() - 2))
  }

  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
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  def recursive(input: Long): Long = {
    if (input < 10) input else input % 10 + recursive(input / 10)
  }

  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  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 primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


object Main {

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

    val N = sc.nextInt()
    println((N - 2) * 180)
  }

}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val n  = in.nextInt
  val r  = List.fill(n)(in.next -> in.nextInt)

  r.zipWithIndex
    .sortWith(
      (x, y) =>
        if (x._1._1 == y._1._1) {
          x._1._2 >= y._1._2
        } else if (x._1._1 <= y._1._1) {
          true
        } else {
          false
        }
    )
    .map(_._2 + 1)
    .foreach(println)
}

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val n  = in.nextInt
  val r  = List.fill(n)(in.next -> in.nextInt).zipWithIndex

  r.sortWith((x, y) => {
      if (x._1._1 == y._1._1) {
        x._1._2 >= y._1._2
      } else if (x._1._1 <= y._1._1) {
        true
      } else {
        false
      }
    })
    .map(_._2 + 1)
    .foreach(println)
}


//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 = {
    println(Array.fill(sc.nextInt())((sc.next(), sc.nextLong()))
      .zipWithIndex
      .sortWith((a, b) => if (a._1._1 == b._1._1) a._1._2 > b._1._2 else a._1._1 < b._1._1)
      .map(a => a._2 + 1).mkString("\n"))
  }

  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
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  def recursive(input: Long): Long = {
    if (input < 10) input else input % 10 + recursive(input / 10)
  }

  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  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 primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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


import java.util.Scanner

object Main {

  def read() = {
    val sc = new Scanner(System.in)
    val n, k = sc.nextInt()
    val v = IndexedSeq.fill(n)(sc.nextInt())
    (n, k, v)
  }

  def solve(n: Int, k: Int, v: IndexedSeq[Int]): Int = {

    (for (deqTimes <- 0 to k; deqRightTimes <- 0 to deqTimes) yield {
      // 右側から何回撮るか
      val deqLeftTimes = deqTimes - deqRightTimes
      // [0, l), [n-r, n)
      val deqLeft = (0 until deqLeftTimes).map(v)
      val deqRight = (n - deqRightTimes until n).map(v)
      val deq = IndexedSeq.concat(deqLeft, deqRight).sorted

      val enqTimes = k - deqTimes
      // 負のやつ捨てる
      val result = deq.zipWithIndex.map {
        case (v, i) => if (i < enqTimes && v < 0) 0 else v
      }.sum
      result
    }).max
  }

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

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


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

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

  val N = in.next().toInt
  val s = new Array[Int](N)
  for (i <- 0 until N)
    s(i) = in.next().toInt

  //
  var ans = 0L
  for (c <- 1 to N-2) { // c := A - B
    var score = 0L

    val dp = new Array[Boolean](N)
    dp(0) = true; dp(N-1) = true

    var x = 1
    breakable {
      while (true) {
        if (x*c >= N)
          break

        if (dp(x*c))
          break
        dp(x*c) = true

        if (dp((N-1)-x*c))
          break
        dp((N-1)-x*c) = true

        score += s(x*c)
        score += s((N-1)-x*c)

        ans = Math.max(ans, score)

        x += 1
      }
    }
  }

  println(ans)
}

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

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

Score : 600 points

Problem Statement

There is an infinitely large pond, which we consider as a number line.
In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1.
On the lotus at coordinate i, an integer s_i is written.

You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:

1. Choose positive integers A and B. Your score is initially 0.

2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

4. Go back to step 2.

You want to end the game with as high a score as possible.
What is the score obtained by the optimal choice of A and B?

Constraints

3 \leq N \leq 10^5

-10^9 \leq s_i \leq 10^9

s_0=s_{N-1}=0

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
s_0 s_1 ...... s_{N-1}

Output

Print the score obtained by the optimal choice of A and B.

Sample Input 1

5
0 2 5 1 0

Sample Output 1

3

If you choose A = 3 and B = 2, the game proceeds as follows:

Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1.

Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2.

Move to coordinate 1 + 3 = 4. The game ends with a score of 3.

There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2 without drowning later.

Sample Input 2

6
0 10 -7 -4 -13 0

Sample Output 2

0

The optimal strategy here is to land the final lotus immediately by choosing A = 5 (the value of B does not matter).

Sample Input 3

11
0 -4 0 -99 31 14 -15 -39 43 18 0

Sample Output 3

59


object Main extends App {

  val Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  var a: Array[Int] = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  (1 to m).foreach { _ =>
    val Array(b, c) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val cc: Array[Int] = Array.fill(b)(c)
    a ++= cc
  }

  println(a.sorted.takeRight(n).map(_.toLong).sum)
}

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


object Main extends App {
  val (r, d, x) = scala.io.StdIn.readLine.split(' ').map(_.toInt) match { case Array(ir, id, ix) => (ir, id, ix) }

  (1 to 10).foldLeft(Seq.empty[Int])((results, i) => results :+ (r * results.lastOption.getOrElse(x) - d)).foreach(println)
}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val r = sc.nextInt
    val D = sc.nextInt
    val x2000 = sc.nextInt
    calc(1, x2000, r, D)
  }

  def calc(count: Int, x: Int, r: Int, D: Int): Int = count match {
    case count if count > 10 => x
    case _ => {
      val result = r * x - D
      println(result)
      calc(count + 1, result, r, D)
    }
  }
}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt()
  val g = Array.fill(m)((sc.nextInt() to sc.nextInt()).toSet)
  val ans = g.foldLeft((1 to n).toSet)((x, y) => x & y)
  println(ans.size)
}

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


import scala.io.{StdIn => in}

object Main extends App {
  val Array(n, m) = in.readLine.split(" ").map(_.toInt)

  val (l, r) = Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foldLeft(0, n) { (acc , e) =>
      (acc._1 max e(0), acc._2 min e(1))
    }

  val ans = (r - l + 1) max 0
  println(ans)
}


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val N = sc.nextInt
    val M = sc.nextInt
    val L = new Array[Int](M)
    val R = new Array[Int](M)
    for (i <- 0 until M) {
      L(i) = sc.nextInt
      R(i) = sc.nextInt
    }

    val maxL = L.max
    val minR = R.min

    val ans =
      if (maxL <= minR) {
        minR - maxL + 1
      } else {
        0
      }

    println(ans)
  }
}


object Main {

  import java.util.Scanner

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val writer = new java.io.PrintWriter(System.out)
    writer.println(solve(sc))
    writer.flush()
  }

  def solve(sc: Scanner): String = {
    val (n, m) = (sc.nextInt(), sc.nextInt())
    val gates = IndexedSeq.fill(m)((sc.nextInt(), sc.nextInt()))
    debug(n, m, gates)

    val leftMax = gates.map { case (l, _) => l }.max
    val rightMin = gates.map { case (_, r) => r }.min
    (if (leftMax > rightMin) 0 else rightMin - leftMax + 1).toString
  }

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


object Main extends App {

  val Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  var a: Array[Long] = scala.io.StdIn.readLine.split(" ").map(_.toLong).sorted

  val bc = (1 to m).map { _ =>
    val Array(b, c) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

    (b, c.toLong)
  }.sortWith((o1, o2) => o1._2 > o2._2)

  var inx = 0
  bc.foreach { bbcc =>
    var cnt = bbcc._1
    val cc = bbcc._2
    while (cnt > 0 && inx < a.length && a(inx) < cc) {
      a.update(inx, cc)
      inx += 1
      cnt -= 1
    }
    // println(a.deep)
  }
  println(a.sum)
}

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

The output may not fit into a 32-bit integer type.


// import scala.io.{StdIn => in}
import java.io._
import scala.collection.{mutable => mu}

object Main extends App {
  import MapHelper._

  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(n, m) = in.readLine.split(" ").map(_.toInt)
  val map = mu.HashMap.empty[Long,Int]

  in.readLine.split(" ").map(_.toLong).foreach(map.addOrUpdate(_,1))
  Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foreach(e => map.addOrUpdate(e(1), e(0)))

  val keys = map.keys.toArray.sorted(Ordering[Long].reverse)
  def rec(acc:Long, cnt:Int, i:Int):Long = {
    val v = keys(i)
    val p =  map(keys(i))
    if(cnt + p >= n) acc + v * (n - cnt)
    else rec(acc + v * p, cnt + p, i + 1)
  }

  val ans = rec(0, 0, 0)
  println(ans)

  object MapHelper {
    implicit class AddOrUpdate[A](map:mu.HashMap[Long,Int]) {
      def addOrUpdate(key:Long, value:Int):mu.HashMap[Long,Int] =
      {
        if(map.contains(key)) map(key) += value
        else map += (key -> value)
        map
      }
    }
  }
}


object Main extends App {

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

  (1 to m).foreach { _ =>
    val Array(b, c) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    (1 to b).foreach { _ =>
      a = a :+ c
    }
  }

  println(a.sorted.takeRight(n).map(_.toLong).sum)

}


import scala.io.{StdIn => in}
import scala.collection.{mutable => mu}

object Main extends App {
  import MapHelper._

  val Array(n, m) = in.readLine.split(" ").map(_.toInt)
  val a = in.readLine.split(" ").map(_.toLong)
  val map = mu.HashMap.empty[Long,Int]

  a.foreach { i =>
    map.addOrUpdate(i, 1)
  }

  Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foreach { e =>
      map.addOrUpdate(e(1),e(0))
    }

  var i = 0
  var cnt = 0
  var acc = 0L
  val keys = map.keys.toArray.sorted(Ordering[Long].reverse)
  val end = keys.size
  while(cnt <= n) {
    cnt += map(keys(i))
    // println(keys(i) + " " + map(keys(i)))
    if(cnt <= n) acc += keys(i) * map(keys(i))
    else if(cnt > n) acc += keys(i) *(map(keys(i)) - (cnt - n))
    i += 1
  }
  val ans = acc
  println(ans)

  object MapHelper {
    implicit class AddOrUpdate[A](map:mu.HashMap[Long,Int]) {
      def addOrUpdate(key:Long, value:Int):mu.HashMap[Long,Int] =
      {
        if(map.contains(key)) map(key) += value
        else map += (key -> value)
        map
      }
    }
  }
}


import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val N, M = sc.nextInt()
    val As = List.fill(N)(sc.nextLong)
    val l = List.fill(M, 2)(sc.nextLong).map(a => (a.head.toInt, a.tail.head))

    val r = l.foldLeft(As){
      case (pre, (num, v))=>
        val s = pre.sorted
        val (less, remain) = s.splitAt(num)
        less.map(a => if (a < v) v else a) ::: remain
    }

    println(r.sum)
  }
}


//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 _, K = sc.nextInt()
    val S = sc.next()
    println(S.take(K - 1) + S.charAt(K - 1).toLower + S.drop(K))
  }

  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
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  def recursive(input: Long): Long = {
    if (input < 10) input else input % 10 + recursive(input / 10)
  }

  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  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 primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val nk = sc.nextLine().split(" ")
    val s = sc.nextLine()
    val t = nk(1).toInt-1

    println(s.updated(t, s(t).toUpper))
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._

    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val S = readLine()
    println(S.updated(k-1, S(k-1).toLower))
  }

}


//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 N = sc.nextInt()
    val X: Int = N % 100;
    val Y: Int = N / 100;

    println(if (calc(X, Y) && calc(Y, X)) "AMBIGUOUS" else if (calc(X, Y)) "YYMM" else if (calc(Y, X)) "MMYY" else "NA")
  }

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

  def calc(S: Int, T: Int): Boolean = {
    S match {
      case 1 => 1 <= T && T <= 31
      case 2 => 1 <= T && T <= 29
      case 3 => 1 <= T && T <= 31
      case 4 => 1 <= T && T <= 30
      case 5 => 1 <= T && T <= 31
      case 6 => 1 <= T && T <= 30
      case 7 => 1 <= T && T <= 31
      case 8 => 1 <= T && T <= 31
      case 9 => 1 <= T && T <= 30
      case 10 => 1 <= T && T <= 31
      case 11 => 1 <= T && T <= 30
      case 12 => 1 <= T && T <= 31
      case _ => false
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  def recursive(n: Long, k: Long): Long = {

    if (n == 1) k else recursive(n - 1, k) * k % 1000000007L
  }

  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  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 primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


object Main {
  def main(args: Array[String]): Unit = {
    val array = Array("YYMM", "MMYY", "AMBIGUOUS", "NA")
    val sc = new java.util.Scanner(System.in)
    val nk = sc.nextLine()
    val f = nk.substring(0, 2)
    val l = nk.substring(2, 4)
    val fb = f.toInt >= 1 && f.toInt < 13
    val lb = l.toInt >= 1 && l.toInt < 13

    if (fb && lb) { println(array(2)) }
    else if (!fb && !lb){ println(array(3)) }
    else if (!fb && lb) { println(array(0)) }
    else if (fb && !lb) { println(array(1)) }
  }
}


import scala.collection.mutable.HashMap

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val N = sc.nextInt
    case class Edge(to: Int, d: Int)
    val tree = new HashMap[Int, Array[Edge]]()
    for (i <- 0 until N - 1) {
      val u = sc.nextInt - 1
      val v = sc.nextInt - 1
      val w = sc.nextInt
      if (tree.contains(u)) {
        tree(u) :+= Edge(v, w)
      } else {
        tree += u -> Array(Edge(v, w))
      }
      if (tree.contains(v)) {
        tree(v) :+= Edge(u, w)
      } else {
        tree += v -> Array(Edge(u, w))
      }
    }

    val colorMap = new HashMap[Int, Int]()

    def dfs(node: Int, depth: Int): Unit = {
      if (colorMap.contains(node)) {
        return
      } else {
        colorMap += node -> depth % 2
      }
      for (connected <- tree(node)) {
        dfs(connected.to, depth + connected.d)
      }
    }

    dfs(0, 0)

    for (i <- 0 until N) {
      println(colorMap(i))
    }
  }

}

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


object Main {

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

    val N = sc.nextInt()

    val distance = Array.fill(N, N)(-1L)

    (0 until N - 1).map { _ =>
      val u, v = sc.nextInt()
      val w = sc.nextLong()
      (u - 1, v - 1, w % 2)
    } foreach { e =>
      val (u, v, w) = e
      distance(u)(v) = w.toLong
      distance(v)(u) = w.toLong
    }

    val visited = new Array[Boolean](N)
    val color = new Array[Int](N)

//    def dfs(u: Int): Unit =
//      if (!visited(u)) {
//        visited(u) = true
//        (0 until N) foreach { v =>
//          if (distance(u)(v) == 0) {
//            color(v) = color(u)
//            dfs(v)
//          } else if (distance(u)(v) == 1) {
//            color(v) = 1 - color(u)
//            dfs(v)
//          }
//        }
//      }
//
//    dfs(0)
    color.foreach(println)
  }

}


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {

  // u: from
  // v: to
  case class Edge(u: Int, v: Int, w: Long)

  def read() = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val edges = IndexedSeq.fill(n-1)(Edge(sc.nextInt(), sc.nextInt(), sc.nextInt()))
    (n, edges)
  }

  def solve(n:Int, edges:IndexedSeq[Edge]): IndexedSeq[Int] = {
    val nextList = IndexedSeq.fill(n+1)(ArrayBuffer.empty[Edge])
    for(edge <- edges){
      val from = edge.u
      val to = edge.v
      nextList(from).append(edge)
      nextList(to).append(Edge(to, from, edge.w))
    }
    val visited = Array.fill(n+1)(false)
    // 1から
    visited(1) = true
    val open: java.util.Queue[Int] = new java.util.ArrayDeque[Int]()
    //add, remove
    open.add(1)
    //白:false ,黒:true
    val colors = Array.fill(n+1)(true)
    colors(1) = false

    while(!open.isEmpty){
      val current = open.remove()
      for(edge <- nextList(current)){
        val next = edge.v
        if(!visited(next)) {
          val w = edge.w
          if (w % 2 == 0) {
            colors(next) = colors(current)
          } else {
            colors(next) = !colors(current)
          }
          visited(next) = true
          open.add(next)
        }
      }
    }
    colors.takeRight(n).map(p => if(p) 1 else 0)
  }

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


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {

  class UnionFind(val n: Int) {

    sealed trait Node

    final case class Root(count: Int, rank: Int) extends Node

    final case class NonRoot(parentIndex: Int) extends Node

    // TODO ArrayBufferではなくArrayでいいはず
    private val nodes: ArrayBuffer[Node] = ArrayBuffer.fill(n)(Root(count = 1, rank = 0))

    private def rootNode(index: Int): (Int, Root) = {
      nodes(index) match {
        case root: Root => (index, root) // nodes(index) == root
        case nonRoot: NonRoot =>
          val (rootIndex, root) = rootNode(nonRoot.parentIndex)
          nodes(index) = NonRoot(parentIndex = rootIndex) // 経路圧縮
          (rootIndex, root)
      }
    }

    def numComponents(): Int = nodes.count(p = node => node.isInstanceOf[Root])

    private def root(index: Int): Int = rootNode(index)._1

    def sameCount(x: Int): Int = rootNode(x)._2.count

    def same(x: Int, y: Int): Boolean = root(x) == root(y)

    def unite(x: Int, y: Int): Unit = {
      if (same(x, y)) return

      val (xRootIndex, xRoot) = rootNode(x)
      val (yRootIndex, yRoot) = rootNode(y)

      if (xRoot.rank < yRoot.rank) {
        // xRootの親をyRootとする
        nodes(xRootIndex) = NonRoot(parentIndex = yRootIndex)
        nodes(yRootIndex) = yRoot.copy(count = xRoot.count + yRoot.count)
      } else {
        // yRootの親をxRootとする
        nodes(yRootIndex) = NonRoot(parentIndex = xRootIndex)
        val nextXRootRank = xRoot.rank + (if (xRoot.rank == yRoot.rank) 1 else 0)
        nodes(xRootIndex) = Root(count = xRoot.count + yRoot.count, rank = nextXRootRank)
      }
    }

  }

  case class Magic(x: Int, y: Int, z: Long)

  case class NextInfo(v: Int, w: Long)

  def read() = {
    val sc = new Scanner(System.in)
    val n, m = sc.nextInt()
    // 0-index化
    val magics = IndexedSeq.fill(m)(
      Magic(sc.nextInt() - 1, sc.nextInt() - 1, sc.nextLong()))
    (n, m, magics)
  }

  def solve(n: Int, m: Int, magics: IndexedSeq[Magic]): Int = {
    val uf = new UnionFind(n)
    for (magic <- magics) {
      uf.unite(magic.x, magic.y)
    }
    uf.numComponents()
  }

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

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

6 5
1 2 1
2 3 2
1 3 3
4 5 4
5 6 5

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


import scala.io.{StdIn => in}

object Main extends App {
  val Array(r, g, b, n) = in.readLine.split(" ").map(_.toInt)

  var cnt = 0
  for {
    i <- 0 to n/r
    j <- 0 to n/g
    k = n - r*i - g*j
    if 0 <= k
  } {
    if(k == 0 && r*i + g*j == n) {
      cnt += 1
      debug(i,j,k)
    }
    else if(k%b == 0 && (r*i + g*j + k) == n) {
      cnt += 1
      debug(i,j,k)
    }
  }

  val ans = cnt
  println(ans)

  def debug(any:Any*):Unit = {
    if(this.getClass.toString != "class Main$")
      println(any.mkString(" "))
  }
}

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


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

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = in.readLine().toInt
    val ss = Array.fill(n) {
      in.readLine()
    }

    var count = ss.foldLeft(0) {
      case (acc, s) => acc + s.foldLeft((0, false)) {
        case ((acc, stat), c) => if (c == 'A') {
          (acc, true)
        } else if (stat && c == 'B') {
          (acc + 1, false)
        } else {
          (acc, false)
        }
      }._1
    }

    var ab = ss.count(s => s.startsWith("B") && s.endsWith("A"))
    var a = ss.count(s => !s.startsWith("B") && s.endsWith("A"))
    var b = ss.count(s => s.startsWith("B") && !s.endsWith("A"))
    var continuous = true

    while (continuous) {
      if (a > 0 && ab > 0) {
        val diff = Math.min(ab, a)
        ab -= diff
        count += diff
      } else if (b > 0 && ab > 0) {
        val diff = Math.min(ab, b)
        ab -= diff
        count += diff
      } else if (ab > 1) {
        count += ab / 2
        ab = ab % 2
      } else if (a > 0 && b > 0) {
        val diff = Math.min(a, b)
        a -= diff
        b -= diff
        count += diff
      } else {
        continuous = false
      }
    }

    out.println(count)

    out.flush()
  }
}

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail
  val sub = ls.foldLeft(0L){ (a,e) =>
    val tmp = (0 until e.size-1).count(j => (e(j)=='A' && e(j+1)=='B'))
    //println(tmp)
    a + tmp
  }
  val fb = ls.count(_.head == 'B')
  val la = ls.count(_.last == 'A')
  val ret = sub + Math.min(fb, la)
  println(ret)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val as = Array.fill(n)(sc.nextLong())

    val absArray = as.map(math.abs)
    val absMin = absArray.min
    val amountOfNegative = as.count(_ < 0)

    val ans = if (amountOfNegative % 2 == 0) {
      absArray.sum
    } else {
      absArray.sum - absMin * 2
    }

    println(ans)
  }

  def debug(args: Any*): Unit = {
    Console.err.println(args.mkString(" "))
  }
}

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

The output may not fit into a 32-bit integer type.


import scala.io.StdIn._

object Main extends App {
  val n = readInt
  val s = readLine.toString
  if (s.count(_ == '#') == 0)
    println(0)
  val ns = s.substring(s.indexOf('#'), s.length - 1)
  println(ns.count(_ == '.'))
}

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


object Main extends App {
  var a = readInt
  var get = readLine
  var sum = 0
  var check = 0
  if(a!=0){
  for(i <- 0 to get.size - 1){
    if(get(i) == '#') {
      check = 1
    } else if (check == 1 && get(i) != '#'){
      sum = sum + 1
    } else {
      check = 0
    }
  }
  }
  println(sum)
}


object Main{
	def main(args:Array[String]){
		val s = new java.util.Scanner(System.in)
		val n = s.nextInt
		val t = s.next
		val b,w = Array.fill(n+2)(0)

		for(i <- 0 to n - 1)
			b(i+1) = b(i) + (if(t.charAt(i) == '#') 1 else 0)
		for(i <- n-1 to 0 by -1)
			w(i+1) = w(i+2) + (if(t.charAt(i) == '.') 1 else 0)

//		println(b.mkString(" "))
//		println(w.mkString(" "))

		println((0 to n).map(i=>b(i)+w(i+1)).min)
	}
}


object Main{
	def main(args:Array[String]){
		val s = new java.util.Scanner(System.in)
		s.nextInt
		val v = s.next

		//println(v.replaceFirst("^\\.+",""))
		//println(v.replaceFirst("#+$",""))
		println(math.min(
			v.replaceFirst("^\\.*","").toCharArray.count('.' ==),
			v.reverse.replaceFirst("^#*","").toCharArray.count('#' ==)
		))
	}
}


object Main extends App {
  var a = readInt
  var get = readLine
  var sum = 0
  var check = 0
  for(i <- 0 until get.size){
    if(get(i) == '#') {
      check = 1
    } else if (check == 1 && get(i) != '#'){
      sum = sum + 1
    } else {
      check = 0
    }
  }
  println(sum)
}


import scala.io._
object Main extends App {
  val Array(a, b, c) = StdIn.readLine.split(" ").map(_.toInt)
  println(if ((a > c && c > b) || (a < c && c < b)) "Yes" else "No")
}

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


import scala.io.StdIn

object Main extends App {

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

  def solve(A: Int, B: Int, C: Int): String = {
    if (a < c & b > c) {
      "Yes"
    } else if (a > c & b < c) {
      "Yes"
    } else {
      "No"
    }
  }

  println(solve(a, b, c))
}


object Main extends App {
  var n = scala.io.StdIn.readInt()
  var s = scala.io.StdIn.readLine()
  var k = scala.io.StdIn.readInt()

  val word = s.charAt(k - 1)
  val answer = s.map { c =>
    if (c == word) {
      c
    } else {
      "*"
    }
  }.mkString
  print(answer)
}

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


import java.util.Collections

import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    val N = StdIn.readInt
    val S = StdIn.readLine
    var whites = S.count(c => c == '.')
    var blacks = S.count(c => c == '#')

    var wCnt = 0
    var bCnt = 0
    var ans = Int.MaxValue
    for(i <- 0 until N) {
      if (S.charAt(i) == '.') {
        wCnt += 1
      }
      if (S.charAt(i) == '#') {
        bCnt += 1
      }
      ans = Math.min(ans, (whites - wCnt) + bCnt)
    }
    println(ans)

  }
}


object Main extends App {
  var n = scala.io.StdIn.readInt()
  var s = scala.io.StdIn.readLine()

  val firstIndexSharp = s.indexOf("#")
  if(firstIndexSharp < 0) {
    print(0)
  } else {
    val countTarget = s.substring(firstIndexSharp, n)
    val whiteCount = countTarget.count(_ == '.')

    val lastIndexComma = countTarget.lastIndexOf(".")
    val countTarget2 = countTarget.substring(lastIndexComma + 1)
    var blackCount = countTarget2.count(_ == '#')

    if (whiteCount > blackCount) {
      print(blackCount)
    } else {
      print(whiteCount)
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    var button_size = io.StdIn.readLine().split(" ").map{_.toInt}
    var total_coin  = 0

    (0 until 2).foreach { i =>
      if(button_size(0) > button_size(1)) {
        total_coin += button_size(0)
        button_size(0) -= 1
      }
      else {
        total_coin += button_size(1)
        button_size(1) -= 1
      }
    }
    println(total_coin)
  }
}

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)

  val a, b = sc.nextInt()

  if (a == b) {
    println(a + b)
  } else {
    val m = math.max(a, b)
    println(2 * m - 1)
  }

}


object Main {

  // 隣り合うタイルの色を異なる色にする
  // 以下の４通りにする タイルの枚数は10^5,
  // S^2回で10^10なので不可,
  // SlogSなら10^6なので間に合う
  // 0101...01|0
  // 1010...10|1
  // 一回舐めて、最初が黒のパターンと最初が白のパターンで何回変更するかを調べる
  // O(2n)

  val Black = '0'
  val White = '1'

  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val S: List[Char] = readLine().toList

    // 最小を調べる
    def solve(): Int = {
      def change(color: Char): Char =
        if (color == Black) White else Black

      // 前が0なら今回は1にして,前が1なら今回は0にする
      @scala.annotation.tailrec
      def count(lst: List[Char], before: Char, acm: Int): Int =
        if (lst.isEmpty) acm
        else if (before == lst.head) count(lst.tail, change(lst.head), acm + 1)
        else count(lst.tail, lst.head, acm)

      Math.min(count(S.tail, S.head, 0), count(S.tail, change(S.head), 1))
    }

    println(solve())
  }

}

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


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

object Main {

  class Zero(var l: Int, var r: Int) {
    override def toString: String = s"[$l,$r]"
  }

  def main(args: Array[String]): Unit = {
    val Array(n: Int, k: Int) = StdIn.readLine.split(" ").map(_.toInt)
    val as = StdIn.readLine.map(_ == '1')

    val B = ArrayBuffer[Zero]()
    B += new Zero(-1, -1)  // Sentinel
    B += new Zero(-1, -1)

    REP(n) { i =>
      if (!as(i)) {
        if (B.last.l == -1) B.last.l = i
        B.last.r = i
      } else if (B.last.l != -1) {
        B += new Zero(-1, -1)
      }
    }
    if (B.last.l != -1) B += new Zero(-1, -1)
    B.last.l = n
    B.last.r = n

    debug(B.mkString(" "))

    var ans = 0
    REP(B.length - 1) { l =>
      val r = min(l + k + 1, B.length - 1)
      val len = B(r).l - 1 - (B(l).r + 1) + 1
      ans = max(ans, len)
    }
    println(ans)

    debug(n, k)
    as.foreach {i => debugNoNewline(i, "")}
  }

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

  def debug(something: Any): Unit = DEBUG {
    System.err.println(something)
  }
  def debugNoNewline(something: Any): Unit = DEBUG {
    System.err.print(something)
  }

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

}

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


import java.util.Scanner

import scala.annotation.tailrec

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

    val isAccess = antennas.combinations(2).map{
      case List(a, b) => b - a
    }.forall(_ <= k)
    if (isAccess) println("Yay!") else println(":(")
  }
}

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


object Main extends App {

  val a = io.StdIn.readLine.toInt
  val b = io.StdIn.readLine.toInt
  val c = io.StdIn.readLine.toInt
  val d = io.StdIn.readLine.toInt
  val e = io.StdIn.readLine.toInt
  val k = io.StdIn.readLine.toInt

  val s = Seq(a,b,c,d,e)

  var isNG = false
  for (i <- 0 until s.size ; j <- i+1 until s.size) {
    if (s(j) - s(i) > k) isNG = true
  }

  if (isNG)
    println(":(")
  else
    println("Yay!")
}


import scala.math.ceil

object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val t = Array.fill(5)(sc.nextInt())
  val last = t.map(x => x % 10).filter(x => x != 0).min
  val up = t.map(x => (ceil(x.toDouble / 10) * 10).toInt).sum
  println(up - (10 - last))
}

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


import scala.io.StdIn._

object Main extends App {

  val D = Array.fill(5)(readInt())

  def solve() = {
    val lastDishIndex = D.zipWithIndex.collect {
      case (minutes, i) if minutes % 10 != 0 => (minutes % 10, i)
    }.sortBy(_._1).map(_._2).headOption
    lastDishIndex match {
      case None => D.sum
      case Some(idx) => {
        D.zipWithIndex.foldLeft(0) { case (acc, (minutes, i)) =>
          if(i == idx) acc + D(i)
          else acc + D(i) + losTime(D(i))
        }
      }
    }
  }

  def losTime(t: Int): Int = {
    if(t % 10 == 0) 0
    else 10 - (t % 10)
  }

  println(solve())

}


object Main {
  def main(args: Array[String]): Unit = {
    var cuisine_list = Vector.empty[Int]
    cuisine_list = cuisine_list :+ io.StdIn.readInt()
    cuisine_list = cuisine_list :+ io.StdIn.readInt()
    cuisine_list = cuisine_list :+ io.StdIn.readInt()
    cuisine_list = cuisine_list :+ io.StdIn.readInt()
    cuisine_list = cuisine_list :+ io.StdIn.readInt()
    var sum_time      = 0
    var min_last_time = 100

    (0 until cuisine_list.length).foreach { i =>
      val last_time = cuisine_list(i)%10
      if(last_time < min_last_time && last_time != 0) min_last_time = last_time
      sum_time += (cuisine_list(i)/10.0 + 0.9).toInt*10
    }
    if(min_last_time == 100) min_last_time = 0
    println(sum_time - 10 + min_last_time)

  }
}


import java.util.Scanner

object Main {
  val sc = new Scanner(System.in)
  def main(args: Array[String]): Unit = {
    val ts = List.fill(5)(sc.nextInt)
    val rm = ts.map(_ % 10).filter(_ != 0)
    val r  = if(rm.nonEmpty) rm.min else 0

    val res = ts.map(t => (t+ 9)/10 * 10).sum - 10 + r

    println(res)

  }
}