import java.lang.Math.max

fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val d = Array(n) {
        readLine()!!.toInt() / 10
    }

    fun isPossibleToReach(): Boolean {
        var current = 0
        for (i in d.indices) {
            if (current < i) return false
            current = max(current, i + d[i])
        }
        return current >= d.size
    }

    if (!isPossibleToReach()) {
        println("no")
        return
    }
    d.reverse()
    if (!isPossibleToReach()) {
        println("no")
        return
    }
    println("yes")
}

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

Trampoline

A plurality of trampolines are arranged in a line at 10 m intervals. Each trampoline has its own maximum horizontal distance within which the jumper can jump safely. Starting from the left-most trampoline, the jumper jumps to another trampoline within the allowed jumping range. The jumper wants to repeat jumping until he/she reaches the right-most trampoline, and then tries to return to the left-most trampoline only through jumping. Can the jumper complete the roundtrip without a single stepping-down from a trampoline?

Write a program to report if the jumper can complete the journey using the list of maximum horizontal reaches of these trampolines. Assume that the trampolines are points without spatial extent.

Input

The input is given in the following format.

N
d_1
d_2
:
d_N

The first line provides the number of trampolines N (2 ≤ N ≤ 3 × 105). Each of the subsequent N lines gives the maximum allowable jumping distance in integer meters for the i-th trampoline d_i (1 ≤ d_i ≤ 106).

Output

Output "yes" if the jumper can complete the roundtrip, or "no" if he/she cannot.

Sample Input 1

4
20
5
10
1

Sample Output 1

no

Sample Input 2

3
10
5
10

Sample Output 2

no

Sample Input 3

4
20
30
1
20

Sample Output 3

yes

Submitted source-code file size, in bytes.

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

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


import java.util.*

fun main(args: Array<String>) {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    var m = sc.nextInt()
    var ans = m

    for (i in 1..n) {
        m += sc.nextInt() - sc.nextInt()
        if (m < 0) { ans = 0; break }
        ans = Math.max(ans, m)
    }
    println(ans)
}

問題 1

　n 分間にわたり，
トンネルの入口と出口で，
1分間に通過する車の数を数えたデータがある．
そのデータは，
全部で n+2 行からなり，
各行には次の内容が書かれている．

第1行目には，正整数 n が書かれており，
調査時間が n 分間であったことを表している．

第2行目には，正整数 m が書かれており，
調査開始時におけるトンネル内の車の台数が m であったことを表している．

第(2+i)行目（ i = 1, 2, ... , n ) には，
調査開始後 (i-1) 分経過した時点から i 分経過するまでの1分間に，
入口を通過した車の台数と出口を通過した車の台数が
１つの空白で区切られて書かれている．

調査開始後 j 分経過した時点 ( j=0, 1, 2, ... , n )
におけるトンネル内の車の台数を Sj とする．
Sj の最大値を出力しなさい．
また，
トンネル内の車の台数が負になることは考えられないので，
Sj が一度でも負になった場合は，
「エラー」の意味で 0 を出力しなさい．
ただし，
n は 10000 以下で，
トンネルの入口および出口を1分間に通過する車の台数は 100 以下である．

　出力ファイルにおいては，
出力の最後の行にも改行コードを入れること．

入出力例

入力例１

3
2
2 3
2 3
4 1

出力例１

3

入力例２

3
2
2 3
2 4
4 1

出力例２

0

入力例３

3
2
2 3
2 3
1 0

出力例３

2

問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


import java.util.*
fun main(args: Array<String>?): Unit {
    val (n, m) = readLine()!!.trim().split(' ').map(String::toInt)
    val edges = Array(m){
        val (a, b, c) = readLine()!!.trim().split( ' ').map(String::toInt)
        Edge(it, a - 1, b - 1, c)
    }
    solve(n, m, edges)
}
fun solve(n: Int, m: Int, edges: Array<Edge>) {
    val nodes = Array(n){ arrayListOf<Edge>()}
    for (e in edges){
        nodes[e.from].add(e)
    }
    val minFromStart = LongArray(n){Long.MAX_VALUE shr 2}.also{it[0] = 0}
    val queue = PriorityQueue<Pair<Int, Long>>(compareBy(Pair<*, Long>::second)).also{it.add(Pair(0, 0))}
    while (queue.isNotEmpty()) {
        val (current, cost) = queue.poll()
        if (minFromStart[current] == cost) {
            for (e in nodes[current]) if (minFromStart[e.to] > e.cost + cost) {
                minFromStart[e.to] = e.cost + cost
                queue.add(Pair(e.to, e.cost + cost))
            }
        }
    }
    for (i in nodes.indices) nodes[i] = arrayListOf()
    for (e in edges){
        nodes[e.to].add(e)
    }
    val minToGoal = LongArray(n){Long.MAX_VALUE shr 2}.also{it[1] = 0}
    queue.add(Pair(1, 0))
    while(queue.isNotEmpty()) {
        val (current, cost) = queue.poll()
        if (minToGoal[current] == cost) {
            for (e in nodes[current]) if (minToGoal[e.from] > e.cost + cost) {
                minToGoal[e.from] = e.cost + cost
                queue.add((Pair(e.from, e.cost + cost)))
            }
        }
    }
    val isBottleNeck = markBottleNeckEdge(n, m, edges, minFromStart, minToGoal)
    for (e in edges) {
        if (isBottleNeck[e.id]) {
            println("SAD")
        }else if (minFromStart[e.to] + minToGoal[e.from] + e.cost < minFromStart[1]){
            println("HAPPY")
        }else {
            println("SOSO")
        }
    }
}
fun markBottleNeckEdge(n: Int, m: Int, edges: Array<Edge>, minCostFromStart: LongArray, minCostToGoal: LongArray): BooleanArray {
    val nodes = Array(n){arrayListOf<FlowEdge>()}
    val minCost = minCostFromStart[1]
    for (e in edges) if (minCostFromStart[e.from] + e.cost + minCostToGoal[e.to] == minCost) {
        nodes[e.from].add(FlowEdge(e.id, e.to, nodes[e.to].size, true))
        nodes[e.to].add(FlowEdge(e.id, e.from, nodes[e.from].size - 1, false))
    }
    val prevEdge = Array(n){null as FlowEdge?}
    val queue: Queue<Int> = ArrayDeque()
    queue.add(0)
    while(queue.isNotEmpty() && queue.peek() != 1) {
        for (e in nodes[queue.poll()]) if (e.hasFlow && prevEdge[e.to] == null) {
            prevEdge[e.to] = e
            queue.add(e.to)
        }
    }
    var last = 1
    while (last != 0) {
        val e = prevEdge[last]!!
        val r = nodes[e.to][e.pair]
        e.hasFlow = false
        r.hasFlow = true
        last = r.to
    }
    queue.clear()
    queue.add(0)
    prevEdge.fill(null)
    prevEdge[0] = nodes.first().first()
    val visited = ArrayDeque<Int>().also{it.add(0)}
    while(queue.isNotEmpty() && queue.peek() != 1) {
        for (e in nodes[queue.poll()]) if (e.hasFlow && prevEdge[e.to] == null) {
            prevEdge[e.to] = e
            queue.add(e.to)
            visited.add(e.to)
        }
    }
    if (queue.isNotEmpty()) {
        return BooleanArray(m){false}
    }
    val result = BooleanArray(m){false}
    var bottleNeck = -1
    for (v in visited) {
        for (e in nodes[v]) {
            if (!e.hasFlow && prevEdge[e.to] == null) {
                bottleNeck = e.id
            }
        }
    }
    while(bottleNeck != -1) {
        visited.clear()
        queue.clear()
        result[bottleNeck] = true
        prevEdge[edges[bottleNeck].to] = nodes.first().first()
        queue.add(edges[bottleNeck].to)
        visited.add(edges[bottleNeck].to)
        bottleNeck = -1
        while(queue.isNotEmpty()) {
            for (e in nodes[queue.poll()]) if (e.hasFlow && prevEdge[e.to] == null) {
                prevEdge[e.to] = e
                queue.add(e.to)
                visited.add(e.to)
            }
        }
        for (v in visited) {
            for (e in nodes[v]) {
                if (!e.hasFlow && prevEdge[e.to] == null && edges[e.id].to == e.to) {
                    bottleNeck = e.id
                }
            }
        }
    }
    return result
}
class Edge(val id: Int, val from: Int, val to: Int, val cost: Int)
class FlowEdge(val id: Int, val to: Int, val pair: Int, var hasFlow: Boolean)

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], skipTags: ["script","noscript","style","textarea","code"], processEscapes: true }});

Problem F
Pizza Delivery

Alyssa is a college student, living in New Tsukuba City. All the streets in the city are one-way. A new social experiment starting tomorrow is on alternative traffic regulation reversing the one-way directions of street sections. Reversals will be on one single street section between two adjacent intersections for each day; the directions of all the other sections will not change, and the reversal will be canceled on the next day.

Alyssa orders a piece of pizza everyday from the same pizzeria. The pizza is delivered along the shortest route from the intersection with the pizzeria to the intersection with Alyssa's house.

Altering the traffic regulation may change the shortest route. Please tell Alyssa how the social experiment will affect the pizza delivery route.

Input

The input consists of a single test case in the following format.

$n$ $m$
$a_1$ $b_1$ $c_1$
...
$a_m$ $b_m$ $c_m$

The first line contains two integers, $n$, the number of intersections, and $m$, the number of street sections in New Tsukuba City ($2 \leq n \leq 100 000, 1 \leq m \leq 100 000$). The intersections are numbered $1$ through $n$ and the street sections are numbered $1$ through $m$.

The following $m$ lines contain the information about the street sections, each with three integers $a_i$, $b_i$, and $c_i$ ($1 \leq a_i n, 1 \leq b_i \leq n, a_i \ne b_i, 1 \leq c_i \leq 100 000$). They mean that the street section numbered $i$ connects two intersections with the one-way direction from $a_i$ to $b_i$, which will be reversed on the $i$-th day. The street section has the length of $c_i$. Note that there may be more than one street section connecting the same pair of intersections.

The pizzeria is on the intersection 1 and Alyssa's house is on the intersection 2. It is guaranteed that at least one route exists from the pizzeria to Alyssa's before the social experiment starts.

Output

The output should contain $m$ lines. The $i$-th line should be

HAPPY if the shortest route on the $i$-th day will become shorter,

SOSO if the length of the shortest route on the $i$-th day will not change, and

SAD if the shortest route on the $i$-th day will be longer or if there will be no route from the pizzeria to Alyssa's house.

Alyssa doesn't mind whether the delivery bike can go back to the pizzeria or not.

Sample Input 1

4 5
1 3 5
3 4 6
4 2 7
2 1 18
2 3 12

Sample Output 1

SAD
SAD
SAD
SOSO
HAPPY

Sample Input 2

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

Sample Output 2

SOSO
SAD
SOSO
SAD
SOSO

Sample Input 3

10 14
1 7 9
1 8 3
2 8 4
2 6 11
3 7 8
3 4 4
3 2 1
3 2 7
4 8 4
5 6 11
5 8 12
6 10 6
7 10 8
8 3 6

Sample Output 3

SOSO
SAD
HAPPY
SOSO
SOSO
SOSO
SAD
SOSO
SOSO
SOSO
SOSO
SOSO
SOSO
SAD


import java.math.BigDecimal

data class CutParams(val m:Int, val n:Int) {
    val left:BigDecimal = BigDecimal(m).divide(BigDecimal(m).add(BigDecimal(n)), 30, BigDecimal.ROUND_HALF_UP)
    val right:BigDecimal = BigDecimal(n).divide(BigDecimal(m).add(BigDecimal(n)), 30, BigDecimal.ROUND_HALF_UP)
}
fun main(args:Array<String>):Unit{
    val (m, n, x) = readLine()!!.split(' ').map(String::toInt)
    val (k, l, y) = readLine()!!.split(' ').map(String::toInt)
    val vertical = CutParams(m, n)
    val horizontal = CutParams(k, l)
    var ver = BigDecimal.ONE
    repeat(x) {
        ver = with(vertical){ver * (left * left + right * right) + left * right}
    }
    var hor = BigDecimal.ONE
    repeat(y){
        hor = with(horizontal){hor * (left * left + right * right) + left * right}
    }
    println(ver * hor)
}

Planarian Regeneration

Problem

皆さん、「プラナリア」って知っていますか？

プラナリアとは、日本では川の上流の石や枯葉などの裏に張り付いて生息している水生生物です。

プラナリアの最も優れた能力はその「再生能力」です。プラナリアの再生能力は著しく、例えば、三等分するとそれぞれが再生し、数週間後には元の完全な状態のプラナリアが3匹できあがります。

この度、会津の山奥の上流にて発見された新種のプラナリアの姿は長方形をしていて、プラナリアはある法則により再生します。
このとき、プラナリアは下の図のように配置し、２つの手段でプラナリアの切断実験を行います。

まず１つ目の手段として、垂直方向に切ることを考えます。一度の切断では、すべての断片を水平方向の長さが(断片の頭に近い部分):(断片の頭に遠い部分)=m :n になるように切断します。この動作をx 回繰り返します。

次に２つ目の手段として、水平方向に切ることを考えます。一度の切断では、すべての断片を垂直方向の長さが(断片の右端に近い部分):(断片の左端に近い部分)=k :l に切断します。この動作をy 回繰り返します。これらの切断によって断片が移動することはありません。

数週間後に、各断片が元の完全なプラナリアの状態に再生している確率は以下の式により求まります。

上の図は、垂直方向に1:2で2回、水平方向に1:1で1回切断した状態です。

以上の操作で切断した時の、数週間後に元の姿に再生しているプラナリアの数の期待値を求めてください。元のプラナリアの垂直方向の長さと水平方向の長さはともに1とします。

Input

m n x
k l y

入力では、6つの整数m , n , x , k , l , y が上記の入力フォーマットで与えられます。

これら6つの整数は問題文中のものと対応しており、水平方向にm :n で切断する動作をx 回、垂直方向にk :l で切断する動作をy 回繰り返します。

1 ≤ m , n , k , l ≤ 100、 0 ≤ x , y ≤ 40 であり、 m , n と l , k はそれぞれ互いに素です。

Output

一行に数週間後に元の姿に再生しているプラナリアの数の期待値を出力してください。

出力は 10-6 以下の誤差ならば許容されます。

Sample Input 1

1 1 1
1 1 1

Sample Output 1

0.562500

Sample Input 2

1 2 2
1 1 1

Sample Output 2

0.490741

Sample Input 3

1 2 0
3 4 0

Sample Output 3

1.000000

Notes

この問題では、doubleよりも精度の高い浮動小数を使用することを推奨します。


import java.util.Scanner;

fun main(args: Array<String>) {
	val scanner = Scanner(System.`in`)
	val ans = mutableListOf<String>()
	while (true) {
		val n = scanner.nextInt()
		if (n==0) break
		val map = mutableMapOf<Char, Int>()
		var max = Pair('-', 0)
		var second = 0
		var win: Pair<Char, Int>? = null
		for (i in 1..n) {
			val c = scanner.next().toCharArray()[0]
			map[c] = map.getOrElse(c){0} + 1
			if (map[c]!! > max.second) max = Pair(c, map[c]!!)
			else if (map[c]!! > second) second = map[c]!!
			val r = n-i
			if (max.second > second+r) {
				win = Pair(max.first, i)
				repeat(r) {scanner.next()}
				break
			}
		}
		if (win!=null) ans.add("${win.first} ${win.second}")
		else ans.add("TIE")
	}
	ans.forEach { println(it) }
}

Look for the Winner!

The citizens of TKB City are famous for their deep love in elections and vote counting.
Today they hold an election for the next chairperson of the electoral commission.
Now the voting has just been closed and the counting is going to start.
The TKB citizens have strong desire to know the winner as early as possible during vote counting.

The election candidate receiving the most votes shall be the next chairperson.
Suppose for instance that we have three candidates A, B, and C and ten votes.
Suppose also that we have already counted six of the ten votes and the vote counts of A, B, and C are four, one, and one, respectively.
At this moment, every candidate has a chance to receive four more votes and so everyone can still be the winner.
However, if the next vote counted is cast for A, A is ensured to be the winner since A already has five votes and B or C can have at most four votes at the end.
In this example, therefore, the TKB citizens can know the winner just when the seventh vote is counted.

Your mission is to write a program that receives every vote counted, one by one, identifies the winner, and determines when the winner gets ensured.

Input

The input consists of at most 1500 datasets, each consisting of two lines in the following format.

n

c1 c2 … cn

n in the first line represents the number of votes, and is a positive integer no greater than 100.
The second line represents the n votes, separated by a space.
Each ci (1 ≤ i ≤ n) is a single uppercase letter, i.e. one of 'A' through 'Z'.
This represents the election candidate for which the i-th vote was cast.
Counting shall be done in the given order from c1 to cn.

You should assume that at least two stand as candidates even when all the votes are cast for one candidate.

The end of the input is indicated by a line containing a zero.

Output

For each dataset, unless the election ends in a tie, output a single line containing an uppercase letter c and an integer d separated by a space:
c should represent the election winner and d should represent after counting how many votes the winner is identified.
Otherwise, that is, if the election ends in a tie, output a single line containing `TIE'.

Sample Input

1
A
4
A A B B
5
L M N L N
6
K K K K K K
6
X X X Y Z X
10
A A A B A C A C C B
10
U U U U U V V W W W
0

Output for the Sample Input

A 1
TIE
TIE
K 4
X 5
A 7
U 8


fun main(args: Array<String>) {
    val n = readLine()?.toInt() ?: return
    val fibonacci = Fibonacci()
    println(fibonacci.getFibonacci(n))
}

class Fibonacci {
    private val fibonacciMemo = mutableMapOf(0 to 1, 1 to 1)

    fun getFibonacci(n: Int): Int {
        return if (fibonacciMemo[n] != null) {
            fibonacciMemo[n]!!
        } else {
            fibonacciMemo[n] = getFibonacci(n - 2) + getFibonacci(n - 1)
            fibonacciMemo[n]!!
        }
    }
}

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

Fibonacci Number

Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:

\begin{equation*}
fib(n)= \left \{
\begin{array}{ll}
1　 & (n = 0) \\
1　 & (n = 1) \\
fib(n - 1) + fib(n - 2) & \\
\end{array}
\right.
\end{equation*}

Input

An integer $n$ is given.

output

Print the $n$-th fibonacci number in a line.

Constraints

$0 \leq n \leq 44$

Sample Input 1

3

Sample Output 1

3


import java.util.Scanner

fun main(args: Array<String>) {
  val sc = Scanner(System.`in`)
  val n = sc.nextInt()
  val array = IntArray(n){sc.nextInt()}
  for (i in 1 until array.size) {
    println(array.joinToString(" "))
    val v = array[i]
    var j = i - 1
    while (j >= 0 && array[j] > v) {
      array[j+1] = array[j]
      j--
    }
    array[j+1] = v
  }
  println(array.joinToString(" "))
}

Insertion Sort

Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key

Note that, indices for array elements are based on 0-origin.

To illustrate the algorithms, your program should trace intermediate result for each step.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by a single space.

Output

The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 2 4 6 1 3

Sample Output 1

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

Sample Input 2

3
1 2 3

Sample Output 2

1 2 3
1 2 3
1 2 3

Hint

Template in C


fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val array = (1..n).map {
        readLine()!!.toInt()
    }

    println(array.asSequence().filter { isPrime(it) }.count())
}

fun isPrime(n: Int): Boolean {
    when (n) {
        0 -> return false
        1 -> return false
        else -> {
            for (i in 2..Math.sqrt(n.toDouble()).toInt())
                if (n % i == 0)
                    return false
            return true
        }
    }
}

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val xs = readLine()!!.split(' ').map { it.toInt() }.toMutableList()
    var cnt = 0
    for (i in 0 until n) {
        for (j in n - 1 downTo i + 1) {
            if (xs[j] < xs[j - 1]) {
                val t = xs[j]
                xs[j] = xs[j - 1]
                xs[j- 1] = t
                cnt++
            }
        }
    }
    println(xs.joinToString(" "))
    println(cnt)
}

Bubble Sort

Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by spaces characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9


class Stack<T>(size: Int) {

    private val elements = arrayOfNulls<Any?>(size)

    private var top = 0

    private fun isEmpty() = top == 0

    private fun isFull() = elements.size == top

    fun push(element: T) {
        if (isFull()) throw Exception("error")
        elements[top] = element
        top++
    }

    @Suppress("UNCHECKED_CAST")
    fun pop() : T {
        if (isEmpty()) throw Exception("error")
        val element = elements[top - 1]
        elements[top - 1] = null
        top--
        return element as T
    }
}

fun isNumber(num: String): Boolean {
    try {
        num.toInt()
    } catch (e: NumberFormatException) {
        return false
    }
    return true
}

fun calc(firstNumber: Int, secondNumber: Int, operator: String): Int {
    when (operator) {
        "+" -> return firstNumber + secondNumber
        "-" -> return firstNumber - secondNumber
        "*" -> return firstNumber * secondNumber
    }
    return 0
}

fun main(args: Array<String>) {
    val array = readLine()!!.split(" ")
    val stack = Stack<String>(array.size)

    array.forEach { item ->
        if (isNumber(item)) {
            stack.push(item)
        } else {
            val secondNumber = stack.pop()
            val firstNumber = stack.pop()
            val result = calc(firstNumber.toInt(), secondNumber.toInt(), item)
            stack.push(result.toString())
        }
    }
    println(stack.pop())
}

Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free.

Write a program which reads an expression in the Reverse Polish notation and prints the computational result.

An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.

Input

An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.

You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106

Output

Print the computational result in a line.

Constraints

2 ≤ the number of operands in the expression ≤ 100

1 ≤ the number of operators in the expression ≤ 99

-1 × 109 ≤ values in the stack ≤ 109

Sample Input 1

1 2 +

Sample Output 1

3

Sample Input 2

1 2 + 3 4 - *

Sample Output 2

-3

Notes

Template in C


import java.lang.Math.*
import java.util.*

data class Point(val x:Double, val y:Double)
class Line private constructor (private val a:Double, private val b:Double, private val c:Double){ // ay = bx + c
    fun crossPoint(other:Line):Point?{
        return when{
            isPallarel(other) -> null
            else -> {
                val newy = (c * other.b - other.c * b) / (a * other.b - other.a * b) // ab'y - a'by = bb'x - bb'x + cb' - c'b
                val newx = (c * other.a - other.c * a) / (a * other.b - other.a * b) // aa'y - aa'y = a'bx - ab'x + ca' - c'a
                Point(newx, newy)
            }
        }
    }
    fun isPallarel(other:Line):Boolean {
        return a * other.b == b * other.a
    }
    fun x(y:Double):Double? {
        return when{
            isHorizontal() -> null
            else -> (a * y - c) / b
        }
    }
    fun x(y:Int):Double? = x(y.toDouble())
    fun y(x:Double):Double? {
        return when{
            isVertical() -> null
            else -> (b * x + c) / a
        }
    }
    fun y(x:Int):Double? = y(x.toDouble())
    fun isHorizontal():Boolean = b == 0e0
    fun isVertical():Boolean = a == 0e0
    companion object {
        fun lineOnTwoPoint(a:Point, b:Point):Line {
            return Line(a.x - b.x, a.y - b.y, b.y * (a.x - b.x) - b.x * (a.y - b.y))
        }
    }
}
data class Vector(val x:Double, val y:Double){
    fun cross(other:Vector):Double = x * other.y - y * other.x
    fun length():Double = sqrt(x * x + y * y)
    companion object {
        fun fromToPoint(from:Point, to:Point):Vector = Vector(to.x - from.x, to.y - from.y)
    }
}
data class Edge(val from:Point, val to:Point)
fun area(a:Point, b:Point):Double {
    return (a.y + b.y) * (a.x - b.x) / 2
}
fun Double.between(a:Double, b:Double):Boolean {
    return (a - this) * (b - this) <= 0
}
fun crossPoint(line:Line, edge:Edge):Point? {
    return line.crossPoint(Line.lineOnTwoPoint(edge.from, edge.to))?.let{
        when{
            it.x.between(edge.from.x, edge.to.x) && it.y.between(edge.from.y, edge.to.y) -> it
            else -> null
        }
    }
}
fun convexArea(points:Array<Point>):Double {
    var res:Double = 0.0
    for (i in 1 until points.size){
        res += area(points[i], points[i - 1])
    }
    return (res + area(points[0], points[points.size - 1])).let{if (it < 0) -it else it}
}
fun cutConvex(points:Array<Point>, from:Point, to:Point):Array<Point> {
    val line = Line.lineOnTwoPoint(from, to)
    val isLeft = Vector.fromToPoint(from, to).cross(Vector.fromToPoint(from, points[0])) > 0
    val (a, b) = points.indices.filter{i ->
        crossPoint(line, Edge(points[i], points[(i + 1) % points.size]))?.let{
            when {
                points[i].x == it.x && points[i].y == it.y -> null
                else -> it
            }
        } != null
    }
    //println("${points[a]}, ${points[a + 1]}, ${crossPoint(line, Edge(points[a], points[a + 1]))}")
    //println("${points[b]}, ${points[(b + 1) % points.size]}, ${crossPoint(line, Edge(points[b], points[(b + 1) % points.size]))}")
    val res = LinkedList<Point>()
    if (isLeft){
        for (i in 0 .. a){
            res.push(points[i])
        }
        res.push(crossPoint(line, Edge(points[a], points[(a + 1) % points.size]))!!)
        res.push(crossPoint(line, Edge(points[b], points[(b + 1) % points.size]))!!)
        for (i in (b + 1) until points.size){
            res.push(points[i])
        }
    }else{
        res.push(crossPoint(line, Edge(points[a], points[(a + 1) % points.size]))!!)
        for (i in (a + 1) .. b){
            res.push(points[i])
        }
        res.push(crossPoint(line, Edge(points[b], points[(b + 1) % points.size]))!!)
    }
    return res.toTypedArray()
}
fun main(args:Array<String>):Unit{
    val n = readLine()!!.toInt()
    val points = Array(n){
        val (x, y) = readLine()!!.split(' ').map(String::toDouble)
        Point(x, y)
    }
    val q = readLine()!!.toInt()
    for (i in 0 until q){
        val (x1, y1, x2, y2) = readLine()!!.split(' ').map(String::toDouble)
        val cut = cutConvex(points, Point(x1, y1), Point(x2, y2))
        println(convexArea(cut))
    }
}

Convex Cut

As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line.

g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon.

Input

The input is given in the following format:

g (the sequence of the points of the polygon)
q (the number of queries = the number of target lines)
1st query
2nd query
:
qth query

g is given as a sequence of points p1,..., pn in the following format:

n
x1 y1
x2 y2
:
xn yn

The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180.

For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y.

Output

For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001.

Constraints

3 ≤ n ≤ 100

1 ≤ q ≤ 100

-10000 ≤ xi, yi ≤ 10000

-10000 ≤ p1x,p1y,p2x,p2y ≤ 10000

No point in g will occur more than once.

p1 ≠ p2

Sample Input

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

Sample Output

2.00000000
4.00000000


import java.math.BigDecimal
import java.util.*
import kotlin.system.measureTimeMillis
//var time = 0L

fun solve(a: Array<Array<Double>>, sortedAxis: Int = -1): Double {
    if (a.size <= 3) {
        var dist = 1000000000000.0
        for ((i, p1) in a.withIndex()) {
            for (p2 in a.takeLast(a.size-i-1)) {
                dist = Math.min(dist, Math.sqrt(Math.pow(p1[0]-p2[0], 2.0)+Math.pow(p1[1]-p2[1], 2.0)))
            }
        }
        return dist
    }

    val mid = a.size/2
    //val startt = System.nanoTime()
    val xSetLen = HashSet(a.map { it -> it[0] }).size
    val (axis1, axis2) = if (xSetLen >= mid) Pair(0, 1) else Pair(1, 0)
    if (axis1 != sortedAxis) a.sortBy { it[axis1] }
    //time += System.nanoTime() - startt

    val leftArray = a.sliceArray(0 until mid)
    val rightArray = a.sliceArray(mid until a.size)
    var delta = Math.min(
            solve(leftArray, axis1),
            solve(rightArray, axis1)
    )
    val median = a[mid][axis1]
    val mid_a = a.filter { it[axis1] in median-delta..median+delta }.sortedBy { it[axis2] }

    for (i in 0 until mid_a.size-1) {
        val ub = mid_a[i][axis2] + delta
        for (j in i+1 until mid_a.size) {
            if (mid_a[i][axis2] >= ub) break
            delta = Math.min(delta,
                    Math.sqrt(Math.pow(mid_a[i][0]-mid_a[j][0], 2.0)+Math.pow(mid_a[i][1]-mid_a[j][1], 2.0)))
        }
    }

    return delta
}

fun main(args: Array<String>) {
    val sc = Scanner(System.`in`)
    val N = sc.nextInt()
    val a = Array(N, { arrayOf(java.lang.Double.parseDouble(sc.next()), java.lang.Double.parseDouble(sc.next())) })
    //val tt = measureTimeMillis {
        val ans = solve(a)
        println(BigDecimal.valueOf(ans).toPlainString())
    //}
    //println(tt)
    //print(time/1000000)
}

Closest Pair

For given n points in metric space, find the distance of the closest points.

Input

n
x0 y0
x1 y1
:
xn-1 yn-1

The first integer n is the number of points.

In the following n lines, the coordinate of the i-th point is given by two real numbers xi and yi. Each value is a real number with at most 6 digits after the decimal point.

Output

Print the distance in a line. The output values should be in a decimal fraction with an error less than 0.000001.

Constraints

2 ≤ n ≤ 100,000

-100 ≤ x, y ≤ 100

Sample Input 1

2
0.0 0.0
1.0 0.0

Sample Output 1

1.000000

Sample Input 2

3
0.0 0.0
2.0 0.0
1.0 1.0

Sample Output 2

1.41421356237


import java.util.*

class UnionFindTree{
    private var mParent:UnionFindTree? = null
    private fun Parent():UnionFindTree {
        return when(mParent) {
            null -> this
            else -> {
                mParent = mParent!!.Parent()
                mParent !!
            }
        }
    }
    fun Join(other:UnionFindTree):Unit {
        if (!IsSameUnion(other)){
            Parent().mParent = other.Parent()
        }
    }
    fun IsSameUnion(other:UnionFindTree):Boolean = Parent() == other.Parent()
}
data class Edge(val from:Node, val to:Node)
class Node(val Id:Int){
    private var mForwardEdges: LinkedList<Node> = LinkedList()
    private var mReverseEdges: LinkedList<Node> = LinkedList()
    fun ForwardEdges():Iterable<Node> = mForwardEdges
    fun ReverseEdges():Iterable<Node> = mReverseEdges
    fun AddEdge(edge:Edge):Unit {
        val (from, to) = edge
        when{
            from == this -> mForwardEdges.push(to)
            to == this -> mReverseEdges.push(from)
        }
    }
}
fun DFS(current:Node, numArray:Array<Int>, init:Int):Int {
    val next = current.ForwardEdges().filter{node -> numArray[node.Id] == -1}
    numArray[current.Id] = 0
    numArray[current.Id] =
            if (next.isEmpty()) init + 1
            else next.fold(init){p, n -> DFS(n, numArray, p)} + 1
    return numArray[current.Id]
}
fun InvDFS(current:Node, uft:Array<UnionFindTree>, isSearched:Array<Boolean>):Unit{
    current.ReverseEdges().forEach {
        when{
             !isSearched[it.Id]  -> {
                isSearched[it.Id] = true
                uft[current.Id].Join(uft[it.Id])
                InvDFS(it, uft, isSearched)
            }
        }
    }
}

fun main(args:Array<String>):Unit{
    val (v, e) = readLine()!!.split(' ').map(String::toInt)
    val nodes = Array(v){Node(it)}
    for (i in 0 until e){
        val (from, to) = readLine()!!.split(' ').map(String::toInt)
        val edge = Edge(nodes[from], nodes[to])
        edge.from.AddEdge(edge)
        edge.to.AddEdge(edge)
    }
    val nums = Array(v){-1}
    nodes.fold(0){ init, node ->
        if (nums[node.Id] == -1)
            DFS(node, nums, init)
        else
            init
    }
    val isSearched = Array(v){false}
    val uft = Array(v){UnionFindTree()}
    nums.withIndex().sortedByDescending { it.value }.map {
        nodes[it.index]
    }.forEach { node ->
        if (!isSearched[node.Id]){
            isSearched[node.Id] = true
            InvDFS(node, uft, isSearched)
        }
    }
    for (i in 0 until readLine()!!.toInt()){
        val (a, b) = readLine()!!.split(' ').map(String::toInt)
        println(if (uft[a].IsSameUnion(uft[b])) 1 else 0)
    }
}

Strongly Connected Components

A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.

Input

A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.

|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1

|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target nodes of i-th edge (directed).

ui and vi represent a pair of nodes given as the i-th query.

Output

For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.

Constraints

1 ≤ |V| ≤ 10,000

0 ≤ |E| ≤ 30,000

1 ≤ Q ≤ 100,000

Sample Input 1

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

Sample Output 1

1
0
1
1


import java.util.*

fun main(args : Array<String>) {

  val scanner = Scanner(System.`in`)
  val s = scanner.nextLine().split(" ") ;

  val x1 = s[0].toDouble()
  val y1 = s[1].toDouble()
  val x2 = s[2].toDouble()
  val y2 = s[3].toDouble()

  val xLine = x2 - x1
  val yLine = y2 - y1

  val line = Math.sqrt( Math.pow(xLine, 2.0) + Math.pow(yLine, 2.0) )

  println("%.8f".format(line))
}

Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356


fun main(args: Array<String>) {
    val S = readLine()!!.toInt()

    println("${S / 3600}:${S % 3600 / 60}:${S % 60}")
}

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

Watch

Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.

Input

An integer $S$ is given in a line.

Output

Print $h$, $m$ and $s$ separated by ':'. You do not need to put '0' for a value, which consists of a digit.

Constraints

$0 \leq S \leq 86400$

Sample Input 1

46979

Sample Output 1

13:2:59


fun sle(a: Int, b: Int): String = when {
  a < b -> "a < b"
  a > b -> "a > b"
  else -> "a == b"
}

fun main(args: Array<String>) {
  val (a,b) = readLine()!!.split(' ').map(String::toInt)

  println(sle(a,b))
}

Small, Large, or Equal

Write a program which prints small/large/equal relation of given two integers a and b.

Input

Two integers a and b separated by a single space are given in a line.

Output

For given two integers a and b, print

a < b

if a is less than b,

a > b

if a is greater than b, and

a == b

if a equals to b.

Constraints

-1000 ≤ a, b ≤ 1000

Sample Input 1

1 2

Sample Output 1

a < b

Sample Input 2

4 3

Sample Output 2

a > b

Sample Input 3

5 5

Sample Output 3

a == b


import java.util.Scanner

fun main(args:Array<String>){
    val cin = Scanner(System.`in`)
    val a = cin.nextInt()
    val b = cin.nextInt()

    if(a > b){
	println("a > b")
    }

    if(a < b){
	println("a < b")
    }

    if(a == b){
	println("a == b")
    }
}


fun main(args: Array<String>) {
    val (a,b,c) = readLine()!!.split(" ").map{ Integer.parseInt(it) }
    println(if(a<b && b<c) "Yes" else "No")
}

Range

Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".

Input

Three integers a, b and c separated by a single space are given in a line.

Output

Print "Yes" or "No" in a line.

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


import java.util.*

fun main(args: Array<String>) {
    val sc = Scanner(System.`in`)
    val r = sc.nextDouble()
    println("${"%.5f".format(Math.PI*r*r)} ${"%.5f".format(2*Math.PI*r)}")
}

Circle

Write a program which calculates the area and circumference of a circle for given radius r.

Input

A real number r is given.

Output

Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-5.

Constraints

0 < r < 10000

Sample Input 1

2

Sample Output 1

12.566371 12.566371

Sample Input 2

3

Sample Output 2

28.274334 18.849556


fun main(args : Array<String>) {
    while (true) {
        val variables = readLine()!!.split(" ")
        val a = variables[0].toInt()
        val op = variables[1]
        val b = variables[2].toInt()

        if ("?" == op) {break}

        when (op) {
            "+" -> println("%d".format(a + b))
            "-" -> println("%d".format(a - b))
            "*" -> println("%d".format(a * b))
            "/" -> println("%d".format(a / b))
        }
    }
}

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

The input consists of multiple datasets. Each dataset is given in the following format.

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108


fun main(argv: Array<String>) {
  val list: MutableList<Int> = mutableListOf()

  loop@ while (true) {
    val inputs = readLine()!!.split(' ')
    val a  = inputs[0].toInt()
    val op = inputs[1]
    val b  = inputs[2].toInt()
    val res = when (op) {
      "+"  -> a+b
      "-"  -> a-b
      "*"  -> a*b
      "/"  -> a/b
      else -> break@loop
    }
    list.add(res)
  }

  for (i in list.indices) {
    println("${list[i]}")
  }
}


fun main(args: Array<String>) {
    while (true){
        val (h, w) = readLine()?.split(" ")?.map { it.toInt() } ?: return
        if (h == 0 && w == 0) return
        for (i in h downTo 1){
            for (j in w downTo 1){
                when{
                    j == 1 -> println("#")
                    i == 1 || i == h || j == w -> print("#")
                    else -> print(".")
                }
            }
        }
        println("")
    }
}

Print a Frame

Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.

##########
#........#
#........#
#........#
#........#
##########

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the frame made of '#' and '.'.

Print a blank line after each dataset.

Constraints

3 ≤ H ≤ 300

3 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
0 0

Sample Output

####
#..#
####

######
#....#
#....#
#....#
######

###
#.#
###


fun main(args: Array<String>) {
	val n = readLine()!!.toInt()
	val a = mutableListOf<String>()

	for (p in listOf('S', 'H', 'C', 'D')) {
		for (i in 1 .. 13) {
			a.add("$p $i")
		}
	}
	for (i in 0 until n) {
		a.remove(readLine())
	}
	if (a.size != 0) println(a.joinToString("\n"))
}

Finding Missing Cards

Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers).

The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond.

Input

In the first line, the number of cards n (n ≤ 52) is given.

In the following n lines, data of the n cards are given. Each card is given by a pair of a character and an integer which represent its suit and rank respectively. A suit is represented by 'S', 'H', 'C' and 'D' for spades, hearts, clubs and diamonds respectively. A rank is represented by an integer from 1 to 13.

Output

Print the missing cards. The same as the input format, each card should be printed with a character and an integer separated by a space character in a line.
Arrange the missing cards in the following priorities:

Print cards of spades, hearts, clubs and diamonds in this order.

If the suits are equal, print cards with lower ranks first.

Sample Input

47
S 10
S 11
S 12
S 13
H 1
H 2
S 6
S 7
S 8
S 9
H 6
H 8
H 9
H 10
H 11
H 4
H 5
S 2
S 3
S 4
S 5
H 12
H 13
C 1
C 2
D 1
D 2
D 3
D 4
D 5
D 6
D 7
C 3
C 4
C 5
C 6
C 7
C 8
C 9
C 10
C 11
C 13
D 9
D 10
D 11
D 12
D 13

Sample Output

S 1
H 3
H 7
C 12
D 8

Note

      解説


import java.util.*

/**
 * 行列.
 */
data class Matrix(val elements: List<List<Int>>) {
    /**
     * 行数.
     */
    val row = this.elements.size
    /**
     * 列数.
     */
    val col = if (this.row > 0) this.elements[0].size else 0

    /**
     * 指定された行列の要素を返します.
     * @param row 行
     * @param col 列
     * @return 要素
     */
    fun get(row: Int, col: Int) = this.elements.get(row).get(col)

    /**
     * 行列の掛け算の結果を返します.
     * @param other 乗数の行列
     */
    fun times(other: Matrix): Matrix = Matrix(
        elements.map { e ->
            (0..other.col - 1).map { col ->
                e.foldIndexed(0, {row, acc, a -> acc + a * other.get(row, col)})
            }
        }
    )

    override fun toString(): String =
        this.elements.map { it.joinToString(" ") }.joinToString("\n")
}

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    val A = Matrix((1..n).map {
        (1..m).map { scanner.nextInt() }
    })
    val b = Matrix((1..m).map {
        listOf(scanner.nextInt())
    })
    println(A.times(b))
}

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

Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.

A column vector with m elements is represented by the following equation.

\[
b = \left(
\begin{array}{c}
b_1 \\
b_2 \\
: \\
b_m \\
\end{array}
\right)
\]

A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
A = \left(
\begin{array}{cccc}
a_{11} & a_{12} & ... & a_{1m} \\
a_{21} & a_{22} & ... & a_{2m} \\
: & : & : & : \\
a_{n1} & a_{n2} & ... & a_{nm} \\
\end{array}
\right)
\]

$i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$ $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

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

Sample Output

5
6
9


fun main(args: Array<String>) {
    var count = 0
    while (true) {
        val (n, target) = readLine()?.split(" ")?.map { it.toInt() } ?: return
        if (n == 0 && target == 0) break
        (1..n).forEach { i ->
            (2..n).forEach { j ->
                (3..n).forEach { k ->
                    if (i != j && j != k && k != i && i + j + k == target) {
                        count++
                    }
                }
            }
        }
    }
    println(count / 2)
}

How many ways?

Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to n.

A total sum of the three integers is x.

For example, there are two combinations for n = 5 and x = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

The input consists of multiple datasets. For each dataset, two integers n and x are given in a line.

The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ n ≤ 100

0 ≤ x ≤ 300

Output

For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説


import java.util.Scanner

fun main(args:Array<String>){

    val cin = Scanner(System.`in`)
    var result = Array<Int>(26,{0})

    while(cin.hasNext()){
        var str = cin.nextLine()
	    str = str.toLowerCase()

	    for(i in 0..str.length-1){
	        if(str[i] >= 'a' && str[i] <= 'z'){
	            val x = str[i].toInt() - 'a'.toInt()
	            result[x] = result[x] + 1
	        }
	    }
    }

    for(i in 'a'..'z'){
	println("$i : ${result[i.toInt() - 'a'.toInt()]}")
    }

}

Counting Characters

Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters.

Input

A sentence in English is given in several lines.

Output

Prints the number of alphabetical letters in the following format:

a : The number of 'a'
b : The number of 'b'
c : The number of 'c'
.
.
z : The number of 'z'

Constraints

The number of characters in the sentence < 1200

Sample Input

This is a pen.

Sample Output

a : 1
b : 0
c : 0
d : 0
e : 1
f : 0
g : 0
h : 1
i : 2
j : 0
k : 0
l : 0
m : 0
n : 1
o : 0
p : 1
q : 0
r : 0
s : 2
t : 1
u : 0
v : 0
w : 0
x : 0
y : 0
z : 0


const val EOF = "END_OF_TEXT"

fun main(args: Array<String>) {
    val target = readLine() ?: return
    var count = 0
    while (true) {
        val texts = readLine()?.split(" ")?.map { if(!it.equals(EOF))it.toLowerCase() else it } ?: break
        texts.forEach{
            if(it == target) count++
        }
        if(texts.contains(EOF)) break
    }
    println(count)
}

Finding a Word

Write a program which reads a word W and a text T, and prints the number of word W which appears in text T

T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.

Constraints

The length of W ≤ 10

W consists of lower case letters

The length of T in a line ≤ 1000

Input

In the first line, the word W is given. In the following lines, the text T is given separated by space characters and newlines.

"END_OF_TEXT" indicates the end of the text.

Output

Print the number of W in the text.

Sample Input

computer
Nurtures computer scientists and highly-skilled computer engineers
who will create and exploit "knowledge" for the new era.
Provides an outstanding computer environment.
END_OF_TEXT

Sample Output

3


import java.util.Scanner

fun main(args:Array<String>){

    val cin = Scanner(System.`in`)
    val n = cin.nextInt()
    var taro:Int = 0
    var hanako:Int = 0

    for(i in 1..n){
	    val str1 = cin.next()
	    val str2 = cin.next()
        when{
	        str1 > str2 -> {taro += 3}
	        str1 < str2 -> {hanako += 3}
	        else -> {
		        taro++
		        hanako++
	        }
	    }
    }
    println("${taro} ${hanako}")
}

Card Game

Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card.
The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Input

In the first line, the number of cards n is given. In the following n lines, the cards for n turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Constraints

n ≤ 1000

The length of the string ≤ 100

Output

Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Sample Input

3
cat dog
fish fish
lion tiger

Sample Output

1 7


fun main(args: Array<String>) {
    var str = readLine()!!.toString()
    val q = readLine()!!.toInt()

    (0 until q).forEach { _ ->
        val command = readLine()!!.toString().split(" ")
        val operation = command[0]
        val a = command[1].toInt()
        val b = command[2].toInt()
        val s = str.slice(0 until a)
        val m = str.slice(a..b)
        val e = str.slice(b + 1 until str.length)
        when (operation) {
            "print" -> println(m)
            "reverse" -> str = s + m.reversed() + e
            "replace" -> str = s + command[3] + e
        }
    }
}

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

Transformation

Write a program which performs a sequence of commands to a given string $str$. The command is one of:

print a b: print from the a-th character to the b-th character of $str$

reverse a b: reverse from the a-th character to the b-th character of $str$

replace a b p: replace from the a-th character to the b-th character of $str$ with p

Note that the indices of $str$ start with 0.

Input

In the first line, a string $str$ is given. $str$ consists of lowercase letters. In the second line, the number of commands q is given. In the next q lines, each command is given in the above mentioned format.

Output

For each print command, print a string in a line.

Constraints

$1 \leq $ length of $str \leq 1000$

$1 \leq q \leq 100$

$0 \leq a \leq b < $ length of $str$

for replace command, $b - a + 1 = $ length of $p$

Sample Input 1

abcde
3
replace 1 3 xyz
reverse 0 2
print 1 4

Sample Output 1

xaze

Sample Input 2

xyz
3
print 0 2
replace 0 2 abc
print 0 2

Sample Output 2

xyz
abc


import ImmutableList.*

fun main(args:Array<String>):Unit {
    val list = LinkList()
    repeat(readLine()!!.toInt()){
        val arg = readLine()!!.split(' ').map(String::toInt)
        when(arg.first()){
            0 -> list.insert(arg.last())
            1 -> list.move(arg.last())
            else -> list.erase()
        }
    }
    println(list)
}
fun <T, A:T> ImmutableList<T>.append(value:A):ImmutableList<T> = Cons(value, this)
sealed class ImmutableList<out T>:Iterable<T>{
    override fun iterator(): Iterator<T> {
        return ListIterator(this)
    }
    object Nil:ImmutableList<Nothing>()
    data class Cons<out T>(val head:T, val tail:ImmutableList<T>):ImmutableList<T>()
}
class ListIterator<out T>(private var list:ImmutableList<T>):Iterator<T> {
    override fun hasNext(): Boolean = list is Cons

    override fun next(): T {
        val next = list as Cons
        list = next.tail
        return next.head
    }

}
class LinkList{
    private var mPrev:ImmutableList<Int> = Nil
    private var mNext:ImmutableList<Int> = Nil
    private fun moveForward():Unit {
        val next = mNext as Cons
        mPrev = Cons(next.head, mPrev)
        mNext = next.tail
    }
    private fun moveBackward():Unit {
        val prev = mPrev as Cons
        mPrev = prev.tail
        mNext = Cons(prev.head, mNext)
    }
    fun insert(value:Int):Unit {
        mNext = Cons(value, mNext)
    }
    fun move(value:Int):Unit {
        if (value >= 0){
            repeat(value){moveForward()}
        }else{
            repeat(-value){moveBackward()}
        }
    }
    fun erase():Unit {
        mNext = (mNext as Cons<Int>).tail
    }

    override fun toString(): String {
        return listOf(mPrev.reversed(), mNext).flatten().joinToString ("\n")
    }
}

List

For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor.

insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted element.

move($d$): Move the cursor to the end by $d$, if $d$ is positive. Move the cursor to the front by $d$, if $d$ is negative.

erase(): Delete the element indicated by the cursor. After this operation, the cursor points the element next to the deleted element. In case there is no such element, the cursor should point END.

In the initial state, $L$ is empty and the cursor points END.

Input

The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $x$

or

1 $d$

or

2

where the first digits 0, 1 and 2 represent insert, move and erase operations respectively.

Output

Print all elements of the list in order after performing given operations. Print an element in a line.

Constraints

$1 \leq q \leq 500,000$

The cursor indicates an element of $L$ or END during the operations

Erase operation will not given when the cursor points END

$-1,000,000,000 \leq x \leq 1,000,000,000$

Moving distance of the cursor ($\sum{|d|}$) does not exceed 1,000,000

$L$ is not empty after performing all operations

Sample Input 1

5
0 1
0 2
0 3
1 1
2

Sample Output 1

3
1


fun main(args:Array<String>):Unit {
    val (n, q) = readLine()!!.split(' ').map(String::toInt)
    val vectors = Array(n){Vector()}
    repeat(q){
        val query = readLine()!!.split(' ').map(String::toInt)
        when(query.first()){
            0 -> vectors[query[1]].pushBack(query.last())
            1 -> println(vectors[query.last()].dump())
            else -> vectors[query.last()].clear()
        }
    }
}

class Vector{
    private var mArray:Array<Int> = Array(100){0}
    var size:Int = 0
        private set
    private fun resize():Unit {
        val newArray = Array(mArray.size * 2){0}
        mArray.forEachIndexed { index, i -> newArray[index] = i }
        mArray = newArray
    }
    fun pushBack(value:Int):Unit {
        if (size == mArray.size) resize()
        mArray[size++] = value
    }
    fun clear():Unit {
        size = 0
    }
    fun dump():String {
        return (0 until size).map{mArray[it]}.joinToString(" ")
    }
}

Vector II

For $n$ dynamic arrays $A_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations:

pushBack($t$, $x$): Add element $x$ at the end of $A_t$.

dump($t$): Print all elements in $A_t$.

clear($t$): Clear $A_t$. If $A_t$ is empty, do nothing.

$A_i$ is a 0-origin array and it is empty in the initial state.

Input

The input is given in the following format.

$n$ $q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $t$ $x$

or

1 $t$

or

2 $t$

where the first digits 0, 1 and 2 represent pushBack, dump and clear operations respectively.

Output

For each dump operation, print elements of $A_t$ a line. Separete adjacency elements by a space character (do not print the space after the last element). Note that, if the array is empty, an empty line should be printed.

Constraints

$1 \leq n \leq 1,000$

$1 \leq q \leq 500,000$

$-1,000,000,000 \leq x \leq 1,000,000,000$

The total number of elements printed by dump operations do not exceed 500,000

Sample Input 1

3 13
0 0 1
0 0 2
0 0 3
0 1 -1
0 2 4
0 2 5
1 0
1 1
1 2
2 1
1 0
1 1
1 2

Sample Output 1

1 2 3
-1
4 5
1 2 3

4 5


import kotlin.math.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

private var fs = BufferedReader(InputStreamReader(System.`in`))
private fun readLn() = fs.readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readLong() = readLn().toLong()
private fun readLongs() = readStrings().map { it.toLong() }
private fun readInt() = readLn().toInt()
private fun readInts() = readStrings().map { it.toInt() }
fun main() {
//    val t = readInt()
//    for (tt in 0 until t) {
        solveA()
//    }
}
fun solveA() {
    var K = readInt()
    var ans = ""
    for(i in 0 until K){
        ans += "ACL"
    }
    println(ans)
}

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


import kotlin.math.min

fun main() {
    val (n, m) = readInts()

    val con = Array(n + 1) { it }

    repeat(m) {
        val (a, b) = readInts()

        con[a] = min(con[a], con[b])
        con[b] = min(con[a], con[b])
    }

    println(con.drop(1).distinct().size - 1)
}

private fun readInts() = readLine()!!.split(" ").map { it.toInt() }
private fun readLongs() = readLine()!!.split(" ").map { it.toInt() }

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).


fun main(){
    val (n, m) = readLine()!!.split(" ").map { it.toInt() }
    val tosi = MutableList(n){ MutableList(0){ 0 } }
    for (i in 0 until m){
        val ab = readLine()!!.split(" ").map { it.toInt() }
        tosi[ab[0] - 1].add(ab[1])
        tosi[ab[1] - 1].add(ab[0])
    }
    val flagList = MutableList(n){ 0 }
    val checkList = MutableList(0){ 0 }
    var flag = -1
    fun check(d: Int){
        for (i in 0 until tosi[d-1].size){
            if (flagList[tosi[d-1][i] - 1] == 0) {
                checkList.add(tosi[d-1][i])
                flagList[tosi[d-1][i] - 1] = 1
            }

        }
        checkList.removeAt(0)
        if (checkList.size > 0) check(checkList[0])
    }
    for (i in 0 until n){
        if (flagList[i] == 0){
            flag++
            flagList[i] = 1
            for (j in 0 until tosi[i].size){
                checkList.add(tosi[i][j])
                flagList[tosi[i][j] - 1] = 1
            }
        }
        if (checkList.size > 0) check(checkList[0])

    }
    println(flag)
}


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")
//@file:OptIn(ExperimentalStdlibApi::class)

import java.io.PrintWriter
import java.util.PriorityQueue
import java.util.TreeMap
import kotlin.math.*
import kotlin.random.Random
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
//    val startTime = System.nanoTime()

    val numCases = 1//readInt()
    case@ for(case in 1..numCases) {
//        print("Case #$case: ")

        val n = readInt()
        val I = IntArray(n)
        val Y = IntArray(n)

        for(i in 0 until n) {
            val x = readInt()-1
            val y = readInt()-1

            I[x] = i
            Y[x] = y
        }

        val D = DSU(n)
        val M = PriorityQueue<Entry>(compareBy { it.y })
        for(x in 0 until n) {
            val y = Y[x]
            val i = I[x]
            val cy = if(M.isNotEmpty() && M.element().y < y) M.element().y else y
            while(M.isNotEmpty() && M.element().y < y) {
                D.join(i, M.remove().i)
            }

            M.add(Entry(cy, i))
        }

        for(i in 0 until n) {
            println(D.size(i))
        }
    }

//    iprintln("Time: ${(System.nanoTime() - startTime) / 1000000} ms")
}

data class Entry(val y: Int, val i: Int)

class DSU(n: Int) {
    private val id = IntArray(n) { it }
    private val sz = IntArray(n) { 1 }

    tailrec fun root(v: Int): Int =
        if(id[v] == v) v else {
            id[v] = id[id[v]]
            root(id[v])
        }

    /** @return false if the two vertices are already joined, true if the join operation is successful */
    fun join(u: Int, v: Int): Boolean {
        var ru = root(u)
        var rv = root(v)
        if(ru == rv) return false
        if(sz[ru] < sz[rv]) ru = rv.also { rv = ru }
        id[rv] = ru
        sz[ru] += sz[rv]
        return true
    }

    fun isJoined(u: Int, v: Int) = root(u) == root(v)

    fun size(v: Int) = sz[root(v)]
}

class IntList(initialCapacity: Int = 12) {
    private var _arr = IntArray(initialCapacity)
    private val capacity get() = _arr.size
    var size = 0
        private set
    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size

    constructor(copyFrom: IntArray): this(copyFrom.size) { copyFrom.copyInto(_arr); size = copyFrom.size }
    constructor(copyFrom: Collection<Int>): this(copyFrom.size) { _arr = copyFrom.toIntArray(); size = copyFrom.size }

    fun contentEquals(other: IntList): Boolean {
        return this === other || size == other.size && indices.all { this[it] == other[it] }
    }

    private fun grow(minCapacity: Int = 8) {
        val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1))
        _arr = _arr.copyOf(newCapacity)
    }

    fun ensureCapacity(minCapacity: Int) { if(capacity < minCapacity) grow(minCapacity) }

    operator fun get(index: Int): Int {
        require(index in 0 until size)
        return _arr[index]
    }

    operator fun set(index: Int, value: Int) {
        require(index in 0 until size)
        _arr[index] = value
    }

    fun add(value: Int) {
        if(size == capacity) grow()
        _arr[size++] = value
    }

    fun addAll(list: IntList) {
        ensureCapacity(size + list.size)
        list._arr.copyInto(_arr, size, 0, list.size)
        size += list.size
    }

    fun add(index: Int, element: Int) {
        if(size == capacity) grow()
        _arr.copyInto(_arr, index + 1, index, size)
        size++
        set(index, element)
    }

    fun clear() { size = 0 }

    fun removeAt(index: Int): Int {
        val e = get(index)
        _arr.copyInto(_arr, index, index + 1, size)
        size--
        return e
    }

    fun indexOf(e: Int): Int {
        for(i in 0 until size) if(this[i] == e) return i
        return -1
    }

    fun remove(e: Int): Boolean {
        val i = indexOf(e)
        if(i == -1) return false
        removeAt(i)
        return true
    }

    operator fun iterator() = object: IntIterator() {
        private var pos = 0
        override fun hasNext() = pos < size
        override fun nextInt() = get(pos++)
    }

    inline fun isEmpty() = size == 0
    inline fun isNotEmpty() = size != 0

    fun pop() = _arr[--size]

    fun popToSize(s: Int) {
        require(s >= 0)
        if(s < size) size = s
    }

    fun swap(i: Int, j: Int) { val t = this[i]; this[i] = this[j]; this[j] = t }
    fun reverse() {
        for(i in 0 until size / 2) swap(i, lastIndex - i)
    }

    fun shuffle(rnd: Random = random) { for(i in lastIndex downTo 1) swap(i, rnd.nextInt(i+1)) }
    fun sort() { shuffle(); _arr._sort(0, size) }
    fun sortDescending() { sort(); reverse() }

    fun joinToString(separator: CharSequence) = if(size == 0) "" else let {
        buildString {
            append(it[0])
            for (i in 1 until size) {
                append(separator).append(it[i])
            }
        }
    }

    override fun toString() = "[" + joinToString(", ") + "]"

    fun toIntArray() = _arr.copyOf(size)
    fun toList() = List(size, ::get)

    inline fun first() = get(0)
    inline fun last() = get(lastIndex)
}

inline fun IntList(size: Int, init: (Int) -> Int) = IntList(size).apply {
    for(i in 0 until size) { add(init(i)) }
}
inline fun IntArray.toIntList() = IntList(this)
inline fun Collection<Int>.toIntList() = IntList(this)
inline fun intListOf(vararg values: Int) = IntList(values)

fun IntList.max() = (1 until size).fold(this[0]) { acc, i -> max(acc, this[i]) }
fun IntList.min() = (1 until size).fold(this[0]) { acc, i -> min(acc, this[i]) }
fun IntList.getOrNull(i: Int) = if(i in indices) get(i) else null
inline fun IntList.count(predicate: (Int) -> Boolean) = indices.count { predicate(this[it]) }
fun IntList.copyOf() = IntList(size, ::get)

/** IO */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

const val _BUFFER_SIZE = 1 shl 16
@JvmField val _buffer = ByteArray(_BUFFER_SIZE)
@JvmField var _bufferPt = 0
@JvmField var _bytesRead = 0

tailrec fun readChar(): Char {
    if(_bufferPt == _bytesRead) {
        _bufferPt = 0
        _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE)
    }
    return if(_bytesRead < 0) Char.MIN_VALUE
    else {
        val c = _buffer[_bufferPt++].toChar()
        if (c == '\r') readChar()
        else c
    }
}

fun readLine(): String? {
    var c = readChar()
    return if(c == Char.MIN_VALUE) null
    else buildString {
        while(c != '\n' && c != Char.MIN_VALUE) {
            append(c)
            c = readChar()
        }
    }
}
fun readLn() = readLine()!!

fun read() = buildString {
    var c = readChar()
    while(c <= ' ') {
        if(c == Char.MIN_VALUE) return@buildString
        c = readChar()
    }
    do {
        append(c)
        c = readChar()
    } while(c > ' ')
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) }

/** additional commons */
inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
fun IntArray.sumLong() = fold(0L, Long::plus)

Score : 300 points

Problem Statement

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k.
Rng can perform the following move arbitrarily many times:

move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

1 \leq N \leq 200,000

(x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).

(y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Sample Input 1

4
1 4
2 3
3 1
4 2

Sample Output 1

1
1
2
2

Rng can reach City 4 from City 3, or conversely City 3 from City 4.

Sample Input 2

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

Sample Output 2

3
3
1
1
2
3
2


import java.util.*

fun main() {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    val ds = (1..n*2).map { sc.nextInt() }

    println(calc(ds))
}

fun calc(ds: List<Int>): String {
    var cnt = 0
    var maxCnt = 0
    for(i in ds.indices step 2) {
        if(ds[i] == ds[i+1]) {
            cnt++
        }
        else {
            if(cnt > maxCnt) maxCnt = cnt
            cnt = 0
        }
    }
    if(cnt > maxCnt) maxCnt = cnt
    return if(maxCnt >= 3) "Yes" else "No"
}

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes


import java.util.*
import kotlin.math.*

fun str() = readLine()!!
fun int() = str().toInt()
fun long() = str().toLong()

fun read(d: String = " ") = str().split(d)
fun <T> list(d: String = " ", f: String.() -> T) = read(d).map { f(it) }
fun list() = list { toInt() }

fun <T> MutableList<T>.removeLast() = this.removeAt(this.lastIndex)

const val mod = 1000000007L

fun main() {
    abc000X()
}

fun abc000X() {
    val n = int()
    (1..n).map { (n - 1L) / it }.sum().let { println(it) }
}

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    var ans = 0L
    for (a in 1 until n) {
        for (b in 1 until n) {
            if (a * b >= n) break
            ans++
        }
    }
    println(ans)
}

fun main() {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


fun main() {
    val MOD = 998_244_353
    val (n, k) = nextIntList()
    val s = mutableSetOf<Int>()
    val map = mutableMapOf(1 to 1L)
    repeat(k) {
        val (l, r) = nextIntList()
        (l..r).forEach {
            s.add(it)
        }
    }
    (2..n).forEach { current ->
        var count = 0L
        s.forEach {
            val i = current - it
            if (i <= 0) return@forEach
            count = count.plus(map.getValue(i)).rem(MOD)
        }
        map[current] = count
    }
//    println(s)
//    println(map)
    println(map[n])
}

// # Utils
// ## Input
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextDouble() = next().toDouble()
fun nextList() = next().split(" ")
fun nextIntList() = next().split(" ").map(String::toInt)
fun nextLongList() = next().split(" ").map(String::toLong)
fun nextDoubleList() = next().split(" ").map(String::toDouble)

// ## Array
inline fun <reified T> sizedArray(size: Int, default: T) = Array(size) { default }
inline fun <reified T> sized2DArray(row: Int, column: Int, default: T) = Array(row) { Array(column) { default } }

// ## mod^-1
//    [NOTE] CANNOT use this for 0, mod, 2mod, 3mod ...(return wrong value)
fun modinv(num: Long, mod: Long): Long {
    var a = num
    var b = mod
    var u = 1L
    var v = 0L
    while (b > 0) {
        val t = a.div(b)
        a -= t * b
        a = b.also { b = a } // swap a and b
        u -= t * v
        u = v.also { v = u } // swap u and v
    }
    u %= mod
    if (u < 0) u += mod
    return u
}

fun gcd(x: Int, y: Int): Int {
    fun innerGcd(x: Int, y: Int): Int {
        return if (x % y == 0) y else innerGcd(y, x % y)
    }
    return if (x >= y) innerGcd(x, y) else innerGcd(y, x)
}

fun gcd(x: Long, y: Long): Long {
    fun innerGcd(x: Long, y: Long): Long {
        return if (x % y == 0L) y else innerGcd(y, x % y)
    }
    return if (x >= y) innerGcd(x, y) else innerGcd(y, x)
}

// classes
class UnionFindTree(val size: Int) {
    private val r = sizedArray(size, -1)
    fun root(x: Int): Int {
        if (r[x] < 0) return x
        return root(r[x])
    }

    fun unite(x: Int, y: Int) {
        var rx = root(x)
        var ry = root(y)
        if (rx == ry) return
        if (r[rx] > r[ry]) {
            rx = ry.also { ry = rx }
        }
        r[rx] += r[ry]
        r[ry] = rx
    }

    fun size(x: Int) = -r[root(x)]

    override fun toString(): String {
        return r.joinToString(separator = ", ")
    }
}

Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

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

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.


import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import kotlin.math.max

val br = BufferedReader(InputStreamReader(System.`in`))
val out = PrintWriter(System.out)

fun main() {
    br.use { out.use {
        solve()
        out.flush()
    } }
}

fun solve() {
    val (n, x, m) = readLongList()

    // 何個目の項からループするのかを求める
    val indexMap = mutableMapOf<Long, Int>()
    var cur = x
    var curIndex = 0
    while (indexMap.containsKey(cur) == false) {
        indexMap[cur] = curIndex
        curIndex++
        cur = cur * cur % m
    }
    val loopFromIndex = indexMap[cur]!!

    // ループする前の合計、1ループの合計、1ループの項数
    val sumBeforeLoop = indexMap.filter { it.value < loopFromIndex }.keys.sum()
    val sumOneLoop = indexMap.filter { it.value >= loopFromIndex }.keys.sum()
    val oneLoopSize = indexMap.count() - loopFromIndex

    // ループ開始後のn、ループする数、ループ終了後のn
    val nAfterStartLoop = max(0, n - loopFromIndex)
    val loopCount = nAfterStartLoop / oneLoopSize
    val nAfterEndLoop = nAfterStartLoop % oneLoopSize

    var ans = if (n <= loopFromIndex) 0 else sumBeforeLoop + loopCount * sumOneLoop

    var pre = if (n <= loopFromIndex) x else cur
    val simulateCount = if (n <= loopFromIndex) n.toInt() else nAfterEndLoop.toInt()
    repeat(simulateCount) {
        ans += pre
        pre = pre * pre % m
    }

    out.println(ans)
    return
}

fun readInteger() = Integer.parseInt(br.readLine())
fun readLong() = java.lang.Long.parseLong(br.readLine())
fun readStringList() = br.readLine()!!.split(' ')
fun readIntegerList() = readStringList().map(Integer::parseInt)
fun readLongList() = readStringList().map(java.lang.Long::parseLong)
fun readDoubleList() = readStringList().map(java.lang.Double::parseDouble)

Score : 500 points

Problem Statement

Let us denote by f(x, m) the remainder of the Euclidean division of x by m.

Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

Constraints

1 \leq N \leq 10^{10}

0 \leq X < M \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X M

Output

Print \displaystyle{\sum_{i=1}^N A_i}.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence A begins 2,4,0,0,\ldots Therefore, the answer is 6.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val a = sc.nextLong()
    val b = sc.nextLong()
    val c = sc.nextLong()
    val d = sc.nextLong()
    val arr = arrayOf(a * c, a * d, b * c, b * d)
    println(arr.max())
}

fun main() {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

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

-10^9 \leq c \leq 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 answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


fun main() {
    val n = readLine()?.toLong() ?: return
    val m = (1e9 + 7).toLong()
    if (n == 1L) {
        println("0")
        return
    }
    var a = 1L
    var o = 1L
    var t = 1L
    repeat(n.toInt()) {
        a = a * 10L % m
        o = o * 9L % m
        t = t * 8L % m
    }
    a = (a - o - o + t) % m
    println(a.toString())
}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


import java.util.*
import kotlin.math.*

fun str() = readLine()!!
fun int() = str().toInt()
fun long() = str().toLong()

fun read(d: String = " ") = str().split(d)
fun <T> list(d: String = " ", f: String.() -> T) = read(d).map { f(it) }
fun list() = list { toInt() }

fun <T> MutableList<T>.removeLast() = this.removeAt(this.lastIndex)

const val mod = 1000000007L

fun main() {
    abc000X()
}

fun abc000X() {
    val n = int()
    val a = Array(n) {
        val (t, u) = list()
        t + u to t - u
    }

    val t = a.map { it.first }.sorted()
    val u = a.map { it.second }.sorted()

    println(max(t.last() - t.first(), u.last() - u.first()))
}

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

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

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val a = Array(n) { sc.nextInt() }
    val b = Array(n) { sc.nextInt() }
    val c = Array(n) { 0 }
    var l = 0
    var r = 0
    for (i in 0 until n) {
        while (l < n && a[l] < b[i]) l++
        if (l == n || a[l] != b[i]) continue
        r = maxOf(l, r)
        while (r + 1 < n && a[r + 1] == b[i]) r++
        if (a[n - 1] == b[i]) r = n - 1
        var d1 = l - i
        if (d1 < 0) d1 += n
        var d2 = r - i
        if (d2 < 0) d2 += n
        if (d1 <= d2) {
            c[d1]++
            if (d2 + 1 != n) {
                c[d2 + 1]--
            }
        } else {
            c[0]++
            c[d2 + 1]--
            c[d1]++
        }
    }
    val d = Array(n) { c[0] }
    for (i in 1 until n) {
        d[i] = d[i - 1] + c[i]
    }
    if (d.contains(0)) {
        val sh = (0 until n).first { d[it] == 0 }
        val ans = (0 until n).map { b[(it + sh) % n] }
        println("Yes")
        println(ans.joinToString(" "))
    } else {
        b.reverse()
        val c = Array(n) { 0 }
        var l = n - 1
        var r = n - 1
        for (i in 0 until n) {
            while (r >= 0 && a[r] > b[i]) r--
            if (r < 0 || a[r] != b[i]) continue
            l = minOf(l, r)
            while (l > 0 && a[l - 1] == b[i]) l--
            if (a[0] == b[i]) l = 0
            var d1 = l - i
            if (d1 < 0) d1 += n
            var d2 = r - i
            if (d2 < 0) d2 += n
            if (d1 <= d2) {
                c[d1]++
                if (d2 + 1 != n) {
                    c[d2 + 1]--
                }
            } else {
                c[0]++
                c[d2 + 1]--
                c[d1]++
            }
        }
        val d = Array(n) { c[0] }
        for (i in 1 until n) {
            d[i] = d[i - 1] + c[i]
        }
        if (!d.contains(0)) {
            println("No")
        } else {
            val sh = (0 until n).first { d[it] == 0 }
            val ans = (0 until n).map { b[(it + sh) % n] }
            println("Yes")
            println(ans.joinToString(" "))
        }
    }
}

fun main() {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}

Score : 600 points

Problem Statement

Given are two sequences A and B, both of length N.
A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.

Constraints

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

1\leq A_i,B_i \leq N

A and B are each sorted in the ascending order.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N

Output

If there exist no reorderings that satisfy the condition, print No.

If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.

If there are multiple reorderings that satisfy the condition, you can print any of them.

Sample Input 1

6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1

Yes
2 2 3 1 1 1

Sample Input 2

3
1 1 2
1 1 3

Sample Output 2

No

Sample Input 3

4
1 1 2 3
1 2 3 3

Sample Output 3

Yes
3 3 1 2