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

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

  val N = in.next().toInt
  val A = new Array[Int](N+1)
  for (i <- 1 to N)
    A(i) = in.next().toInt

  //
  def check(num: Int): Int = {
    val memo = new Array[Int](N+1)
    memo(1) = num
    memo(N) = num
    for (i <- 2 to N) {
      val tmp = A(i-1) - memo(i-1)
      memo(i-1) += tmp
      memo(i) += tmp
    }

    val res = A(N) - memo(N)
    Math.abs(res)
  }

  // 下に凸のグラフの最小値
  def ternarySearchInt(small: Int, big: Int): Int = {
    if(big - small <= 2) {
      val mid = (big + small) / 2
      if(check(big) <= check(mid)) big
      else if(check(small) <= check(mid)) small
      else mid
    }
    else{
      val midl = (big + small) / 2
      val midr = midl + 1
      if (check(midl) >= check(midr))
        ternarySearchInt(midl, big)
      else
        ternarySearchInt(small, midr)
    }
  }

  val ans = ternarySearchInt(0, 1e9.toInt)

  val memo = new Array[Int](N+1)
  val com = new Array[Int](N+1)
  memo(1) = ans
  memo(N) = ans
  com(1) = ans
  for (i <- 2 to N) {
    val tmp = A(i-1) - memo(i-1)
    com(i) = tmp
    memo(i-1) += tmp
    memo(i) += tmp
  }

  val res = A(N) - memo(N)
  Math.abs(res)

  pw.print(com(1)*2)
  for(i <- 2 to N)
    pw.print(s" ${com(i)*2}")
  pw.println
  pw.flush()
}

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

Score : 400 points

Problem Statement

There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.

Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).

When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:

Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.

Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.

Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


import java.util.Scanner

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

  val x = d.sorted
  val abc = x(N / 2 - 1)
  val arc = x(N / 2)
  println(arc - abc)
}

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

Score : 300 points

Problem Statement

Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).

He is dividing the problems into two categories by choosing an integer K, as follows:

A problem with difficulty K or higher will be for ARCs.

A problem with difficulty lower than K will be for ABCs.

How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

2 \leq N \leq 10^5

N is an even number.

1 \leq d_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685

Submitted source-code file size, in bytes.

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

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


object Main extends App{
  val n = readInt
  val ds = readLine.split(" ").map(_.toInt).sorted
  println(ds(n/2)-ds(n/2-1))
}


object Main {

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

    val N, K = sc.nextInt()

    // K個の青いボールを回収するために高橋君がちょうどi回操作をする必要がある時
    // 青いボールの置き方と赤いボールの置き方は独立して考えられる
    // N - K個の赤いボールを一列に並べて, N - K + 1個の隙間のどこに青いボールをK個置くかを考える
    // すると, N - K + 1個の隙間から i 個選ぶ選び方は {N-K+1}_C_i 通り
    // その隙間を選んだ後に,　各隙間に何個ボールを入れるかを考えるので
    // K 個のボールの隙間 K - 1 個の中から i - 1 個選ぶのは
    // {K-1}_C_{i-1} 通りあるので, それぞれの掛け合わせで
    // {N-K+1}_C_i * {K-1}_C_{i-1} となる

    def solve(N: Int, K: Int): IndexedSeq[Long] = {
      val MAX: Long = Math.pow(10, 9).toLong + 7
      val nCr = Array.fill(N+1, K+1)(0L)
      for {
        i <- 0 to N
      } {
        nCr(i)(0) = 1
        for {
          j <- 1 to (i min K)
        } nCr(i)(j) = nCr(i-1)(j-1) + nCr(i-1)(j)
      }
      for {
        i <- 1 to K
      } yield (nCr(N-K+1)(i) * nCr(K-1)(i-1)) % MAX
    }

    println(solve(N, K).mkString("\n"))
  }

}

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


//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 {
  val A: Array[Int] = (0 to 100001).toArray

  def solve(sc: => Scanner): Unit = {
    val N, L = sc.nextLong()
    val A = (1L to N).map(i => L + i - 1)
    val B = A.map(i => Math.abs(i)).min
    println(A.sum - (if (A.contains(B)) B else -B))
  }

  def recursive(now: Int, M: Int): Int = {
    if (now > M) -1 else {
      if (A(now) == now) {
        A(now) += 1
        A(now)
      } else {
        val B = recursive(A(now), M)
        if (B == -1) -1 else {
          A(now) = B
          A(now)
        }
      }
    }
  }

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

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

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

  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(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  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 N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    if (args.length > 0 && args(0) == "TEST") {
      println(test())
    } else {
      val input = io.Source.stdin.getLines().mkString("\n")
      println(solve(input).trim())
    }
  }

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val n,l = s.nextInt
    val apples = (l until (l + n))
    val aMin = apples.minBy(Math.abs(_))
    apples.filter(_ != aMin).sum.toString
  }

  val tests = List(
    """5 2""".stripMargin -> """18""",
    """3 -1""".stripMargin -> """0""",
    """30 -50""".stripMargin -> """-1044"""
  )

  def test(): String = tests.map { case (i, o) => (i.trim(), o.trim()) }
    .zipWithIndex.map {
    case ((input, outputExpect), i) =>
      val output = solve(input).trim()
      val tnum = i + 1
      s"test$tnum:" + (
        if (output == outputExpect) "Passed"
        else s"Failed\nexpect:\n$outputExpect\noutput:\n$output")
  }
    .mkString("\n")
}


object Main extends App {
  val input = io.StdIn.readLine().split(" ").map(_.toInt)
  val N = input(0)
  val L = input(1)

  val apples = (1 to N).toArray
  val tastes = apples.map { a => L + a - 1 }
  val totalTaste = tastes.sum
  // 全てが正の時→最小の整数
  // 正と負の時→最小の整数
  // 全てが負の時→最大の整数

  val result = if (tastes.head >= 0) tastes.tail.sum
  else if (tastes.last <= 0) tastes.init.sum
  else {
    var isFound = false
    tastes.foldLeft(scala.collection.mutable.ArrayBuffer.empty[Int]) { (acc, v) =>
      if (isFound) {
        acc += v
      } else {
        if (v >= 0) {
          isFound = true
          acc
        } else {
          acc += v
        }
      }
    }.sum
  }

  println(result)
}


import scala.io.StdIn._

object Main extends App {

  val arr = readLine().split(" ").map(_.toInt)
  val n = arr(0)
  val l = arr(1)
  val ajiArr: Array[Int] = Array.fill(n)(0)
  for(i <- 0 until n){ ajiArr(i) = l + i }
  val removedOne = ajiArr(n-1) match {
    case i if i < 0  => i
    case i if i == 0 => 0
    case _           => ajiArr(0)
  }
  val result = ajiArr.sum - removedOne
  println(result)
}


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, l = sc.nextInt
    val apples = (l until l + n).toList
    println(apples.sum - apples.minBy(_.abs))
  }
}


import scala.io.StdIn

object Main extends App {
  val Array(n, l)  = StdIn.readLine.toString.split(" ").map(_.toInt)

  def solve(n: Int, l: Int) : Int  = {

    val ls = (1 to n).map(l + _ -1)
    var m = Int.MaxValue

    ls.foreach {i =>
      if (Math.abs(m) > Math.abs(i))
        m = i
    }
    ls.sum - m
  }
  println(solve(n, l))

}


import scala.io.StdIn.readLine

object Main extends App {

  readLine.trim.split(' ').map(_.toLong) match {
    case Array(a, b, c, d) =>
      val toB = b - b / c - b / d + b / lcm(c, d)
      val untilA = (a - 1) - (a - 1) / c - (a - 1) / d + (a - 1) / lcm(c, d)
      println(toB - untilA)
    case _ => ???
  }

  def lcm(a: Long, b: Long): Long = {
    a / gcd(a, b) * b
  }
  def gcd(a: Long, b: Long): Long = {
    b match {
      case 0 => a
      case _ => gcd(b, a % b)
    }
  }
}

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.{ArrayList, Collections, Comparator, List => JList}
import scala.math._

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      println(solve(input).trim());
    }
  }

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

  def solve(input: String): String = {
    val a = input.split(" ").head.toLong - 1
    val b = input.split(" ").tail.head.toLong
    val c = input.split(" ").tail.tail.head.toLong
    val d = input.split(" ").tail.tail.tail.head.toLong
    val nc = b / c - a / c
    val nd = b / d - a / d
    val ncd = b / lcm(c, d) - a / lcm(c, d)

    (b - a - (nc + nd - ncd)).toString
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

  val tests=List(
    """4 9 2 3""".stripMargin -> """2
                                   |""".stripMargin,
    """10 40 6 8""".stripMargin -> """23""".stripMargin,
    """314159265358979323 846264338327950288 419716939 937510582""" -> "532105071133627368"
  )

  def test():String= {
    return tests.map{case (i,o)=>(i.trim(),o.trim())}
      .zipWithIndex.map{
      case ((input,outputExpect),i)=>{
        val output=solve(input).trim();
        s"test${i+1}:"+(if(output==outputExpect){
          "Passed"
        }else{
          s"Failed\nexpect:\n${outputExpect}\noutput:\n${output}"
        })
      }}
      .mkString("\n");
  }
}


import scala.io.{StdIn => in}

object Main extends App {
  val Array(a, b, c, d) = in.readLine.split(" ").map(_.toLong)

  val a1 = b / c
  val a2 = a / c
  val b1 = b / d
  val b2 = a / d

  val a3 = a1 - a2
  val b3 = b1 - b2

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

  val lcm = c * d / gcd(c, d)

  val c1 = b / lcm
  val c2 = a / lcm

  val c3 = c1 - c2

  val t = a match {
    case x if a % c == 0 && a % d == 0 && a % lcm == 0 => 3
    case x if a % c == 0 && a % d == 0 => 2
    case x if a % c == 0 && a % lcm == 0 => 2
    case x if a % lcm == 0 && a % d == 0 => 2
    case x if a % c == 0 || a % d == 0 => 1
    case _ => 0
  }
  debug(a3, b3, c3, lcm, t, b-a)
  val ans = ((1 + b - a - t) - (a3 + b3 - c3)) max 0
  println(ans)

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


object Main extends App {
  import scala.io.StdIn._
  val Array(n, k) = readLine.trim.split(' ').map(_.toInt)
  if ((n - 1) * (n - 2) / 2 < k) {
    println("-1")
  }else {
    var rest = (n - 1) * (n - 2) / 2 - k
    println(n - 1 + rest)
    for (i <- 1 until n) {
      println(s"$i $n")
    }
    for (i <- 1 until n; j <- 1 until i) {
      if (rest > 0) {
        println(s"$i $j")
        rest -= 1
      }
    }
  }
}

Score: 500 points

Problem Statement

Does there exist an undirected graph with N vertices satisfying the following conditions?

The graph is simple and connected.

The vertices are numbered 1, 2, ..., N.

Let M be the number of edges in the graph. The edges are numbered 1, 2, ..., M, the length of each edge is 1, and Edge i connects Vertex u_i and Vertex v_i.

There are exactly K pairs of vertices (i,\ j)\ (i < j) such that the shortest distance between them is 2.

If there exists such a graph, construct an example.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq K \leq \frac{N(N - 1)}{2}

Input

Input is given from Standard Input in the following format:

N K

Output

If there does not exist an undirected graph with N vertices satisfying the conditions, print -1.

If there exists such a graph, print an example in the following format (refer to Problem Statement for what the symbols stand for):

M
u_1 v_1
:
u_M v_M

If there exist multiple graphs satisfying the conditions, any of them will be accepted.

Sample Input 1

5 3

Sample Output 1

5
4 3
1 2
3 1
4 5
2 3

This graph has three pairs of vertices such that the shortest distance between them is 2: (1,\ 4), (2,\ 4), and (3,\ 5). Thus, the condition is satisfied.

Sample Input 2

5 8

Sample Output 2

-1

There is no graph satisfying the conditions.


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

import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni()

    val x = ((n-1)*(n-2)) / 2
    if(k > x) out.println(-1)
    else {
      val list = new ListBuffer[(Int, Int)]
      var add = x - k
      REP(n-1, 1) { i =>
        REP(n-1, 1) { j =>
          if(j > i &&  add > 0) {
            list += ((i, j))
            add -= 1
          }
        }
      }
      REP(n-1, 1) { i =>
        list += ((i, n))
      }
      out.println(list.size)
      list.foreach(f => out.println(f._1 + " " + f._2))
    }
  }
}

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  // val a = new Array[Int](N)

  val N, K = in.next().toInt

  if (N == 2) {
    if (K == 0) {
      println(1)
      println(1, 2)
    }
    else {
      println(-1)
    }
  }
  else if (N == 3) {
    if (K == 0) {
      println(3)
      println(1, 2)
      println(2, 3)
      println(3, 1)
    }
    else if (K == 1) {
      println(2)
      println(1, 2)
      println(2, 3)
    }
    else
      println(-1)
  }
  else {
    if (K == N) {
      pw.println(N)
      pw.println(N, 1)
      for (i <- 1 until N)
        pw.println(i, i+1)
    }
    else {
      var tmp = ((N-2) * (N-1)) / 2

      if (tmp < K)
        pw.println(-1)
      else {
        var ans: List[(Int, Int)] = Nil

        for (i <- 2 to N) {
          ans = (i, 1) :: ans
        }

        var l = 2
        var r = 3
        while(tmp > K) {
          ans = (l, r) :: ans

          if (r == N) {
            l += 1
            r = l + 1
          }
          else {
            r += 1
          }

          tmp -= 1
        }

        pw.println(ans.length)
        ans.foreach {case (a, b) => pw.println(s"$a $b")}
      }
    }

    pw.flush()
  }
}

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


object Main {
  def main(args:Array[String]) = {
   // val seq = readLine.split("")
    val input=io.Source.stdin.getLines().mkString("\n")
   // println(solve(input).toString.trim())
    val a = input.split("\n")
    println(solve(a(0),a(1)).toString.trim())
   // print(input)
  }

 def solve(aaa:String,bbb:String): Int={
  var ctm = aaa.split(" ")(0).toInt + 1
  var gl = aaa.split(" ")(1).toInt
  val parr= bbb.split(" ").map(_ .toInt)
  var ps =0
  var ct =1
  for(i<-0 until ctm){
  	if(ps <= gl){
       val ss= if (i!= ctm-1) parr(i) else 0
    	ps = ps + ss
       ct =i
    }
  }
  ct+1
}
}

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


import scala.util.control.Breaks
object Main extends App {
  val read = scala.io.StdIn.readLine()
  val NxArray =  read.split(" ").map(_.toInt).toVector
  var sum = 0
  var count = 1
  val read2 = scala.io.StdIn.readLine()
  val LArray =  read2.split(" ").map(_.toInt).toVector

  val b = new Breaks
  b.breakable{
    LArray.foreach { l =>
      if (sum + l > NxArray(1)) {
        b.break()
      } else {
        count = count + 1
        sum = sum + l
      }

    }
  }
  println(count)

}


object Main extends App {

  val Array(w,h,x,y) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def solve() = {
    val s = w.toDouble * h / 2
    val hasMultiWay = if(x == w.toDouble/2 || x == h.toDouble/2) 1 else 0
    s"$s $hasMultiWay"
  }

  println(solve)

}

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


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[Int]]): 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 Ans(a: Long, b: 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 = {
    val N = ni()
    val A = na(N)
    val neg = A.count(_ < 0)

    val ans = ArrayBuffer[Ans]()
    var x = 0L
    if (neg == 0) {
      sort(A)
      ans += Ans(A(0), A(1))
      x = A(0) - A(1)
      REP(N - 3, 2) { i =>
        ans += Ans(x, A(i))
        x = x - A(i)
      }
      ans += Ans(A(N - 1), x)
      x = A(N - 1) - x

    } else if (N == neg) {
      sort(A)
      ans += Ans(A(N - 1), A(N - 2))
      x = A(N - 1) - A(N - 2)
      REP_r(N - 2) { i =>
        ans += Ans(x, A(i))
        x = x - A(i)
      }
    } else {
      import java.util
      val Pos, Neg = new util.ArrayDeque[Int]
      REP(N) { i =>
        if (A(i) >= 0) Pos.add(A(i))
        else Neg.add(A(i))
      }

      def add(a: Long, b: Long): Unit = {
        x = b - a
        // この先にPosがあるようだとxをマイナスにする
        if (!Pos.isEmpty) {
          if (x >= 0) {
            ans += Ans(a, b)
            x *= -1
          } else {
            ans += Ans(b, a)
          }
        } else {
          // Negしかないようならxをプラスにする
          if (x < 0) {
            ans += Ans(a, b)
            x *= -1
          } else {
            ans += Ans(b, a)
          }
        }
      }
      add(Pos.poll(), Neg.poll())

      def addFromQueue(): Unit = {
        if (!Pos.isEmpty) {
          add(x, Pos.poll())
        } else {
          add(x, Neg.poll())
        }
      }

      REP(N - 3) { _ =>
        addFromQueue()
      }

      addFromQueue()
    }

    out.println(x)
    REP(ans.length) { i =>
      out.println(s"${ans(i).a} ${ans(i).b}")
    }
  }
}

Score : 500 points

Problem Statement

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

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


object Main {
  import Array._
  import scala.io.StdIn.readLine

  def main(args: Array[String]): Unit = {
    val Array(p, q, r) = readLine split(" ") map(_.toInt)
    println(Array(p + q, q + r, r + p).min)
  }
}

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


    object Main extends App {
        var n = readInt
      	var get = readLine.split(" ")
      	var sum1 = 0
      	var sum2 = 0
      var sum3 = 100
      for(i <- 0 to n-2) {
        sum1 = sum1 + get(i).toInt
        for(j <- i+1 to n-1){
          sum2 = sum2 + get(j).toInt
        }
          sum3 = math.min(sum3,math.max(sum1,sum2)-math.min(sum1,sum2))
        sum2=0
      }
           println(sum3)
    }


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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val P, Q, R = ni()
    val rm = max(P, max(Q, R))
    val ans = P + Q + R - rm
    out.println(ans)
  }
}


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  val w = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  var ans = 999999
  (1 until w.length).foreach { i =>
    val a = w.splitAt(i)

    ans = List(Math.abs(a._1.sum - a._2.sum), ans).min
  }
  println(ans)
}

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


object Main {

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

    val H, W = sc.nextInt()
    val S = new Array[String](H)
    var s = 0
    while (s < H) {
      S(s) = sc.next()
      s += 1
    }
    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


object Main {

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

    val H, W = sc.nextInt()
    val S = Array.fill(H)(sc.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)
  }

}


object Main {

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

    val Array(h, w) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val S = (0 until h) map (_ => scala.io.StdIn.readLine())
    println(S.mkString("\n"))
    val dp = Array.fill(h, w, 2)(-1) // 未計算の場合-1, dp(i)(j)(0) 縦の数 dp(i)(j)(1)横の数
    (0 until h) foreach { i =>
      (0 until w) foreach { j =>
        if (S(i)(j) == '.') { // 障害物ではない場合
          if (dp(i)(j)(0) == -1) { // 縦方向未計算の場合のみ計算
            var di = 0
            while (i + di < h && S(i+di)(j) == '.') { // 障害物に当たるか壁に当たるかまで
              di += 1
            }
            (0 until di) foreach { dii =>
              dp(i+dii)(j)(0) = di - 1
            }
          }
          if (dp(i)(j)(1) == -1) { // 横方向未計算の場合のみ計算
            var dj = 0
            while (j + dj < w && S(i)(j+dj) == '.') { // 障害物に当たるか壁に当たるかまで
              dj += 1
            }
            (0 until dj) foreach { djj =>
              dp(i)(j+djj)(1) = dj - 1
            }
          }
        }
      }
    }

    var max = 0
    (0 until h) foreach { i =>
      (0 until w) foreach { j =>
        max = Math.max(max, dp(i)(j)(0) + dp(i)(j)(1) + 1)
      }
    }
    println(max)
  }

}


import java.util.Scanner

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

    val a, p = sc.nextInt()

    val apples = a * 3 + p

    println(apples / 2)

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

  def printExecTime(process: => Unit): Unit = {
    val start = System.currentTimeMillis
    process
    debug("処理時間： " + (System.currentTimeMillis - start) + " ミリ秒")
  }

}

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


object Main extends App {
	val N = scala.io.StdIn.readInt
	val a = new Array[(String, Int, Int)](N)

	for(i<-0 until N){
		val Array(ta, tb) = scala.io.StdIn.readLine.split(" ")
		a(i) = (ta, tb.toInt, i+1)
	}

	val b = a.sortBy(x => (x._1, -x._2))

	for(x <- b){
		println(x._3)
	}

}

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


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {
  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()
  }

  case class Restaurant(num: Int, city: String, score: Int)

  def solve(sc: Scanner): String = {
    val n = sc.nextInt()
    val evaluations = Vector.fill(n)((sc.next(), sc.nextInt())) // (市名, 評価点)
    val restaurants = evaluations.zipWithIndex.map { case ((city, score), i) => Restaurant(i + 1, city, score) }
    debug(n, evaluations)

    val cities = evaluations.map(_._1).sorted.distinct // Vector(kazan, khabarovsk, moscow)

    val restaurantNumBuf = ArrayBuffer.empty[Int]

    cities.foreach { city =>
      restaurants.filter(_.city == city).sortBy(_.score).reverse.foreach { restaurant =>
        restaurantNumBuf += restaurant.num
      }
    }
    debug(restaurantNumBuf)

    restaurantNumBuf.mkString("\n")
  }

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


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    if (args.length > 0 && args(0) == "TEST") {
      println(test())
    } else {
      val input = io.Source.stdin.getLines().mkString("\n")
      println(solve(input).trim())
    }
  }

  def numWithNbits(n: Int): Int = (1 << n) - 1
  def checkBitOn(n: Int, b: Int): Int = (n >> (b - 1)) & 1
  def countBitsOn(n: Int, bl: List[Int]): Int = bl match {
    case Nil => 0
    case bh::bt => checkBitOn(n, bh) + countBitsOn(n, bt)
  }

  def isAllOn(n: Int, is: List[(List[Int], Int)]): Boolean = is match {
    case Nil => true
    case (bits, parity) :: irs =>
      if (countBitsOn(n, bits) % 2 != parity) false
      else isAllOn(n, irs)
  }

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val (n, m) = (s.nextInt, s.nextInt)
    val ks = List.fill(m)(List.fill(s.nextInt)(s.nextInt))
    val ps = List.fill(m)(s.nextInt)
    val is = ks.zip(ps)
    (1 to numWithNbits(n)).count(i => isAllOn(i, is)).toString()
  }

  val tests = List(
    """2 2
      |2 1 2
      |1 2
      |0 1
    """.stripMargin -> """1""",
    """2 1
      |2 1 2
      |0
    """.stripMargin -> """1""",
    """2 3
      |2 1 2
      |1 1
      |1 2
      |0 0 1
    """.stripMargin -> """0""",
    """5 2
      |3 1 2 5
      |2 2 3
      |1 0
    """.stripMargin -> "8"
  )

  def test(): String = tests.map { case (i, o) => (i.trim(), o.trim()) }
    .zipWithIndex.map {
    case ((input, outputExpect), i) =>
      val output = solve(input).trim()
      val tnum = i + 1
      s"test$tnum:" + (
        if (output == outputExpect) "Passed"
        else s"Failed\nexpect:\n$outputExpect\noutput:\n$output")
  }
    .mkString("\n")
}

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


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.toLong*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


import scala.io.{StdIn => in}

object Main extends App {
  val Array(a, b) = in.readLine.split(" ").map(_.toInt)
  val ans = a match {
    case x if x <= 5 => 0
    case x if x <=12 => b / 2
    case _ => b
  }
  println(ans)
}

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.


import scala.io.{StdIn => in}

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

  var l = 1
  var r = n
  Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foreach { e =>
      if(e(0) > l) (l until e(0)).foreach(i => pass(i) = false)
      if(e(1) < r) (e(0) to r).foreach(i => pass(i) = false)
      val x = l max e(0)
      val y = r min e(1)
    }
  val ans = pass.tail.count(_ == true)
  println(ans)
}

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 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 ls = l.foldLeft(List.fill(N)(0L)) {
      case (pre, (num, v)) =>
        val (less, remain) = pre.sorted.splitAt(num)
        less.map(a => if (a < v) v else a) ::: remain
    }*/
    val ls = l.foldLeft(List.empty[Long]) {
      case (pre, (num, v)) => List.fill(num)(v) ::: pre
    }
    /*

    val r = ls.foldLeft(As) {
      case (pre, v) =>
        (v :: pre).sorted.tail
    }

     */
    val r = (ls ::: As).sorted.takeRight(N)

    println(r.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 java.util.Scanner

object Main {

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

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

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

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

  object RR {
    val mod: Long = (1e9 + 7).toLong

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

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

  def comb(a: Int, b: Int): Int = {
    if (a < b) 0
    else if (b == 0) 1
    else comb(a - 1, b - 1) + comb(a - 1, b)
  }

  def fracRR(n: Int): RR = (1 to n).map(RR(_)).foldLeft(RR(1))(_ * _)

  def combRR(n: Int, r: Int): RR = {
    // comb(n,r) = n!/(r! (n-r)!)
    val x = fracRR(n) // n!
    val y = fracRR(r) // r!
    val z = fracRR(n - r) // (n-r)!

    val yz = y * z
    x * rrInv(yz)
  }

  def mypow(x: Long, t: Long): Long = {
    if (t == 0) {
      return 1
    }
    val y = mypow(x, t / 2)
    if (t % 2 == 0) {
      y * y
    } else {
      x * y * y
    }
  }

  def mypowRR(x: RR, t: Long): RR = {
    if (t == 0) {
      return RR(1)
    }
    val y = mypowRR(x, t / 2)
    if (t % 2 == 0) {
      y * y
    } else {
      x * y * y
    }
  }

  def rrInv(x: RR): RR = mypowRR(x, RR.mod - 2)

  def solve(h: Int, w: Int, k: Int): Int = {
    // 1 + 2 + ... + tを求める
    def sum(t: Int) = t * (t + 1) / 2

    def sumDist(x: Int, y: Int): Int = {
      // 0-origin
      // xより左側: [0,x) (xマス)
      // xより右側: [x+1,w) (w-x-1マス)
      // yより上側: [0,y) (yマス)
      // yより下側: [y+1, h) (h-y-1マス)
      (sum(x) + sum(w - x - 1)) * h + (sum(y) + sum(h - y - 1)) * w
    }

    comb(w * h - 2, k - 2) * (for (y <- 0 until h; x <- 0 until w) yield sumDist(x, y) / 2).sum
  }

  def solve2(h: Int, w: Int, k: Int): Long = {
    // 1 + 2 + ... + tを求める
    def sum(t: Long) = t * (t + 1) / 2

    def sumDist(x: Long, y: Long): Long = {
      // 0-origin
      // xより左側: [0,x) (xマス)
      // xより右側: [x+1,w) (w-x-1マス)
      // yより上側: [0,y) (yマス)
      // yより下側: [y+1, h) (h-y-1マス)
      (sum(x) + sum(w - x - 1)) * h + (sum(y) + sum(h - y - 1)) * w
    }

    val result = combRR(w * h - 2, k - 2) * RR((for (y <- 0 until h; x <- 0 until w) yield sumDist(x, y) / 2).sum)
    result.representative
  }

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

Score : 500 points

Problem Statement

We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.

If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:

\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)

Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.

We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.

Constraints

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

2 \leq K \leq N \times M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K

Output

Print the sum of the costs of all possible arrangements of the pieces, modulo 10^9+7.

Sample Input 1

2 2 2

Sample Output 1

8

There are six possible arrangements of the pieces, as follows:

((1,1),(1,2)), with the cost |1-1|+|1-2| = 1

((1,1),(2,1)), with the cost |1-2|+|1-1| = 1

((1,1),(2,2)), with the cost |1-2|+|1-2| = 2

((1,2),(2,1)), with the cost |1-2|+|2-1| = 2

((1,2),(2,2)), with the cost |1-2|+|2-2| = 1

((2,1),(2,2)), with the cost |2-2|+|1-2| = 1

The sum of these costs is 8.

Sample Input 2

4 5 4

Sample Output 2

87210

Sample Input 3

100 100 5000

Sample Output 3

817260251

Be sure to print the sum modulo 10^9+7.


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  val Q = in.next().toInt
  var stack: List[Int] = Nil
  var elem = -1
  var sum = 0L
  var hoge = 0L
  var (minus, zero, plus) = (0, 0, 0)

  for (_ <- 0 until Q) {
    val com = in.next().toInt

    if (com == 1) {
      val a, b = in.next().toInt
      sum += b
      hoge += a.abs
      if (a > 0)
        plus += 1
      else if (a == 0)
        zero += 1
      else
        minus += 1

      stack = a :: stack
      elem += 1
    }
    else {
      val now = stack.sorted.toArray
      val mid = now(elem / 2).toLong

      var ans = sum + hoge

      if (mid > 0)
        ans += mid * (minus - plus + zero)
      else if (mid < 0)
        ans += mid.abs * (plus - minus + zero)

      pw.println(s"$mid $ans")
    }
  }

  pw.flush()
}

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

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


object Main extends App {

  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val s = scala.io.StdIn.readLine()

  def solve() =  {
    s.updated(k-1, s(k-1).toLower)
  }

  println(solve)

}

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


import scala.io.{StdIn => in}

object Main extends App {
  val s = in.readLine

  val month = (1 to 12)
  val first = if(month.contains(s.take(2).toInt)) true else false
  val second = if(month.contains(s.drop(2).toInt)) true else false

  val ans = (first, second) match {
    case (true, true) => "AMBIGUOUS"
    case (true, false) => "MMYY"
    case (false, true) => "YYMM"
    case _ => "NA"
  }
  println(ans)
}

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.


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: Long)
    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.nextLong
      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, Long]()

    def dfs(node: Int, depth: Long): 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 E = Array.fill(N)(new scala.collection.mutable.ArrayBuffer[(Int, Byte)]())
    val ru, rv, rw = sc.nextInt()
    E(ru-1).append((rv-1, (rw % 2).toByte))
    E(rv-1).append((ru-1, (rw % 2).toByte))
    (0 until N - 2) foreach { _ =>
      val u, v, w = sc.nextInt()
      E(u-1).append((v-1, (w % 2).toByte))
      E(v-1).append((u-1, (w % 2).toByte))
    }

    val visited = new Array[Boolean](N)
    val color = new Array[Byte](N)
    color(ru) = 0
    visited(ru) = true

    def dfs(u: Int): Unit =
      E(u) foreach { case (v, w) =>
        if (!visited(v)) {
          visited(v) = true
          if (w == 0) {
            color(v) = color(u)
            dfs(v)
          } else {
            color(v) = (1 - color(u)).toByte
            dfs(v)
          }
        }
      }

    dfs(ru)
    color.foreach(println)
  }

}


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

    (0 until N - 1).map { _ =>
      val u, v, w = sc.nextInt()
      (u - 1, v - 1, w % 2)
    }. foreach { e =>
      val (u, v, w) = e
      distance(u)(v) = w
      distance(v)(u) = w
    }
//
//    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()
    // ここ、0オリジン化した方がいい
    val edges = IndexedSeq.fill(n - 1)(Edge(sc.nextInt(), sc.nextInt(), sc.nextInt()))
    (n, edges)
  }

  def read2() = {
    val input = io.Source.stdin.getLines()
    val n = input.next().toInt
    val edges = IndexedSeq.fill(n - 1) {
      val strs = input.next().split(" ")
      Edge(strs(0).toInt, strs(1).toInt, strs(2).toInt)
    }
    (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 output1(result: IndexedSeq[Int]) = {
    result.foreach(println)
  }

  def output2(result: IndexedSeq[Int]) = {
    result.foreach(System.out.println)
  }

  def output3(result: IndexedSeq[Int]) = {
    val out = new java.io.PrintWriter(System.out)
    result.foreach(out.println)
    out.flush()
  }

  def main(args: Array[String]): Unit = {
    val (n, edges) = read2()
    output3(solve(n, edges))
  }
}


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

object Main extends App {
  val n = in.readInt

  case class edge(v:Int, d:Int)
  val tree = Array.fill(n)(mu.ListBuffer.empty[edge])

  Iterator.continually(in.readLine)
    .take(n-1)
    .map(_.split(" ").map(_.toInt))
    .foreach { e =>
      tree(e(0)-1) :+= new edge(e(1)-1, e(2))
      tree(e(1)-1) :+= new edge(e(0)-1, e(2))
    }

  val colors = Array.ofDim[Int](n)
  val visit = Array.ofDim[Boolean](n)

  def dfs(v:Int, d:Int):Unit = {
    if(!visit(v)) {
      // println("v:" + v + " " + d)
      visit(v) = true
      colors(v) = if(d % 2 == 0) 0 else 1
      for(nv <- tree(v))
        dfs(nv.v, d + nv.d)
    }
  }

  dfs(0,0)
  println(colors.mkString("\n"))
}


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {
  case class Edge(x: Int, y: Int, z: Long)

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

    (n, m, edges)
  }

  def solve2(n: Int, m: Int, edges: IndexedSeq[Edge]): Int = {
    var cnt = 0 // 連結成分数

    val nextList = IndexedSeq.fill(n)(ArrayBuffer.empty[Edge])
    for (edge <- edges) {
      val from = edge.x
      val to = edge.y
      nextList(from).append(edge)
      nextList(to).append(Edge(to, from, edge.z))
    }

    val visited = Array.fill(n)(false)
    for (i <- 0 until n) {
      if (!visited(i)) {
        visited(i) = true
        cnt += 1
        //BFS
        val open: java.util.Queue[Int] = new java.util.ArrayDeque[Int]()
        open.add(i)
        while (!open.isEmpty) {
          val current = open.remove()
          for (edge <- nextList(current)) {
            val next = edge.y
            if(!visited(next)) {
              open.add(next)
              visited(next) = true
            }
          }
        }

      }
    }
    cnt
  }

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

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 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 Array(n, k) = in.readLine().split("\\s+").map(_.toInt)

    out.println(n - k + 1)
    out.flush()
  }
}

Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


import java.io.{PrintWriter, _}
import java.util._

object Main {
  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task
    solver.solve(1, in, out)
    out.close()
  }

  class Task {
    def solve(testNumber: Int, in: InputReader, out: PrintWriter): Unit = {
      val a = in.nextLine.split(" ").map(i => i.toInt)
      var i = 0
      var count = 0
      var res = 0
      while (i < a(0)){
        i += 1
        count += 1
        if (count == a(1)){
          res += 1
          count = 0
          i -= (a(1) - 1)
        }
      }
      println(res)
    }
  }

  class InputReader(val stream: InputStream) extends AutoCloseable {
    //reader = new BufferedReader(new FileReader(stream), 32768);
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer = new StringTokenizer("")

    def next: String = {
      while ( {
        tokenizer == null || !tokenizer.hasMoreTokens
      }) try
        tokenizer = new StringTokenizer(reader.readLine)
      catch {
        case e: IOException =>
          throw new RuntimeException(e)
      }
      tokenizer.nextToken
    }

    def nextLine: String = {
      try
        return reader.readLine
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      ""
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    override def close(): Unit = {
    }
  }

}


import java.util.Scanner

import scala.util.Random

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

  def solve(n:Int, strs: IndexedSeq[String]): Int={
    // AB含み
    // A終わり
    // B始まり
    // A終わりB始まり

    val nContainsAB = strs.map(str => {
      (0 until str.length-1).count(i=> str(i) == 'A' && str(i+1)=='B')
    }).sum
    val nAEnd = strs.count(str => str.last == 'A')
    val nBBegin = strs.count(str => str.head == 'B')
    val nAEndBBegin = strs.count(str => str.last == 'A' && str.head=='B')

    if(nAEndBBegin > 0 && nAEndBBegin == nAEnd && nAEndBBegin == nBBegin){
      nContainsAB + nAEndBBegin - 1
    }else{
      nContainsAB + Math.min(nAEnd, nBBegin)
    }
  }

  def solveNaive(n:Int, strs: IndexedSeq[String]): Int={
    def countAB(str:String) = (0 until str.length-1).count(i=> str(i) == 'A' && str(i+1)=='B')
    strs.permutations.map(pstrs => pstrs.flatten.mkString).map(countAB).max
  }

  def rand(n:Int) = {
    Random.setSeed(123)
    val chars = "ABH"
    val strs =(0 until n).map{ k =>
      val len = Random.nextInt(6) + 1
      (0 until len).map(_=>chars(Random.nextInt(3))).mkString
    }
    println(n)
    strs.foreach(println)
    (n,strs)
  }

  def experiment(n:Int) ={
    for (_ <- 0 until 100){
      val (n, strs) = rand(5)
      val resultNormal = solve(n, strs)
      val resultNaive = solveNaive(n, strs)
      println(s"$resultNormal, $resultNaive, ${resultNormal == resultNaive}")
    }
  }

  def main(args: Array[String]): Unit = {
    val (n, strs) = read()
    //val (n, strs) = rand(5)
    println(solve(n,strs))
    //println(solveNaive(n,strs))
    //experiment(5)
  }
}

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 {

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

     val start = Math.floor((1 + Math.sqrt(4 * N + 1))/2).toLong

     def rec(m: Long, acm: Long): Long =
       if (m < N) {
         if ((N / m) == (N % m)) rec(m + 1, acm + m)
         else rec(m + 1, acm)
       } else acm

     println(rec(start, 0))
   }

}

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.