fun main() {
    val n = readln().toInt()
    val coins = readln().split(" ").map{ it.toInt() }
    var sum = 0
    var count = 0

    coins.sortedDescending()

    for (coin in coins) {
        sum += coin
        count++
        if (sum > coins.sum() - sum) {
            break
        }
    }
    println(count)
}

Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1,a2,...,an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

The first line contains integer n (1≤n≤100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1≤ai≤100) — the coins' values. All numbers are separated with spaces.

In the single line print the single number — the minimum needed number of coins.

In the first sample you will have to take 2 coins (you and your twin have sums equal to 6,0 correspondingly). If you take 1 coin, you get sums 3,3. If you take 0 coins, you get sums 0,6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.
In the second sample one coin isn't enough for us, too. You can pick coins with values 1,2 or 2,2. In any case, the minimum number of coins equals 2.

import java.util.Scanner

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val n = scanner.nextInt();
    var sum = 0
    val arr = mutableListOf<Int>()
    for (i in 0 until n) {
        val x = scanner.nextInt()
        arr.add(x)
        sum += x
    }

    arr.sortDescending()
    var cs = 0
    var cc = 0
    while (arr.size > 0) {
        cs += arr[0]
        cc++
        arr.removeAt(0)
        if (cs > arr.sum()) break
    }
    println(cc)
}


//  A. Comparing Strings

// region Preamble

import java.util.concurrent.ConcurrentHashMap
import kotlin.math.*

// IO
val reader = System.`in`.bufferedReader()
val writer = System.out.bufferedWriter()

fun readLn(): String = reader.readLine()
fun readInt() = readLn().toInt()
fun readLong() = readLn().toLong()
fun readDouble() = readLn().toDouble()
fun readWords() = readLn().split(" ")
fun readInts() = readWords().map { it.toInt() }
fun readLongs() = readWords().map { it.toLong() }
fun readDoubles() = readWords().map { it.toDouble() }
fun readLines(n: Int) = List(n) { readLn() }

fun Boolean.yesNo() = if (this) "YES" else "NO"
fun writeLn(s: String) = writer.write("$s\n")

@JvmName("writeLn1")
fun String.writeLn() = writer.write("\n")

// Functional
fun List<Int>.cumulativeSum1() = runningFold(0) { x, y -> x + y }
fun List<Int>.cumulativeSum() = cumulativeSum1().drop(1)

@JvmName("cumulativeSum1Long")
fun List<Long>.cumulativeSum1() = runningFold(0L) { x, y -> x + y }

@JvmName("cumulativeSumLong")
fun List<Long>.cumulativeSum() = cumulativeSum1().drop(1)

fun <E> List<E>.isDistinct() = size == toSet().size

fun <T> List<T>.histogram() = groupingBy { it }.eachCount().withDefault { 0 }
fun String.histogram() = groupingBy { it }.eachCount().withDefault { 0 }

fun <T> List<T>.groupContiguous(): List<List<T>> {
  val groups = mutableListOf<MutableList<T>>()
  forEach { e ->
    if (e == groups.lastOrNull()?.lastOrNull()) {
      groups.last().add(e)
    } else {
      groups.add(mutableListOf(e))
    }
  }
  return groups
}

fun <T> permutationsWithReplacement(input: Set<T>, n: Int): List<List<T>> =
  if (n <= 0) listOf(emptyList())
  else input.flatMap { first ->
    permutationsWithReplacement(input, n - 1).map { rest ->
      listOf(first) + rest
    }
  }

fun <T> permutations(input: Set<T>): List<List<T>> {
  if (input.isEmpty()) return listOf(emptyList())

  val first = input.first()
  val tail = input.drop(1).toSet()

  return permutations(tail).flatMap { rest ->
    (0..rest.size).map {
      buildList {
        addAll(rest.take(it))
        add(first)
        addAll(rest.drop(it))
      }
    }
  }
}

fun <T> combinations(input: Set<T>, n: Int): Set<Set<T>> {
  if (n <= 0) return setOf(emptySet())
  if (input.isEmpty()) return emptySet()

  val first = input.take(1).toSet()
  val tail = input.drop(1).toSet()

  return combinations(tail, n - 1).map { rest -> first + rest }.toSet() + combinations(tail, n)
}

// Math
fun Int.isOdd() = this % 2 == 1
fun Long.isOdd() = this % 2 == 1L
fun Int.isEven() = !isOdd()
fun Long.isEven() = !isOdd()
fun Int.isZero() = this == 0
fun Long.isZero() = this == 0L
fun Int.isPositive() = this > 0
fun Long.isPositive() = this > 0L
fun Int.isNegative() = this < 0
fun Long.isNegative() = this < 0L
fun Int.isPositiveOrZero() = this >= 0
fun Long.isPositiveOrZero() = this >= 0L
fun Int.isNegativeOrZero() = this <= 0
fun Long.isNegativeOrZero() = this <= 0L

infix fun Int.divides(o: Int) = o % this == 0
infix fun Long.divides(o: Long) = o % this == 0L
infix fun Int.divisibleBy(o: Int) = o divides this
infix fun Long.divisibleBy(o: Long) = o divides this

infix fun Int.floorDiv(o: Int) = floor(toDouble() / o).toInt()
infix fun Long.floorDiv(o: Long) = floor(toDouble() / o).toInt()
infix fun Int.ceilDiv(o: Int) = ceil(toDouble() / o).toInt()
infix fun Long.ceilDiv(o: Long) = ceil(toDouble() / o).toInt()

infix fun Int.mod(m: Int) = ((this % m) + m) % m
infix fun Long.mod(m: Long) = ((this % m) + m) % m

// Number Theory
fun primeSieve(n: Int): List<Boolean> {
  val s = BooleanArray(n + 1) { true }
  val limit = sqrt(n.toDouble()).toInt()
  (2..limit).forEach { i ->
    if (s[i]) (i * i..n).forEach { j -> s[j] = false }
  }
  return s.toList()
}

fun primes(n: Int) = primeSieve(n).mapIndexedNotNull { i, p -> i.takeIf { p } }

// DP
inline fun <I, O> memoize(crossinline fn: (I) -> O): ((I) -> O) = with(ConcurrentHashMap<I, O>()) {
  { input -> get(input) ?: fn(input).also { output -> set(input, output) } }
}
// endregion

fun solve(p: String, q: String): Boolean {
  if (p.length != q.length)
    return false
  val m = p.zip(q).withIndex().filter { (_, v) -> v.first != v.second }.map { it.index }
  if (m.size != 2)
    return false
  val (i, j) = m
  if (j - 1 != i)
    return false
  return p[i] == q[j] && p[j] == q[i]
}

fun main() {
  val (p, q) = readLines(2)
  println(solve(p, q).yesNo())
}

Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.

The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters.
The number of letters in each genome doesn't exceed 10^5. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.

Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".

First example: you can simply swap two letters in string "ab". So we get "ba".  Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".

//  A. Comparing Strings

// region Preamble

import java.util.concurrent.ConcurrentHashMap
import kotlin.math.*

// IO
val reader = System.`in`.bufferedReader()
val writer = System.out.bufferedWriter()

fun readLn(): String = reader.readLine()
fun readInt() = readLn().toInt()
fun readLong() = readLn().toLong()
fun readDouble() = readLn().toDouble()
fun readWords() = readLn().split(" ")
fun readInts() = readWords().map { it.toInt() }
fun readLongs() = readWords().map { it.toLong() }
fun readDoubles() = readWords().map { it.toDouble() }
fun readLines(n: Int) = List(n) { readLn() }

fun Boolean.yesNo() = if (this) "YES" else "NO"
fun writeLn(s: String) = writer.write("$s\n")

@JvmName("writeLn1")
fun String.writeLn() = writer.write("\n")

// Functional
fun List<Int>.cumulativeSum1() = runningFold(0) { x, y -> x + y }
fun List<Int>.cumulativeSum() = cumulativeSum1().drop(1)

@JvmName("cumulativeSum1Long")
fun List<Long>.cumulativeSum1() = runningFold(0L) { x, y -> x + y }

@JvmName("cumulativeSumLong")
fun List<Long>.cumulativeSum() = cumulativeSum1().drop(1)

fun <E> List<E>.isDistinct() = size == toSet().size

fun <T> List<T>.histogram() = groupingBy { it }.eachCount().withDefault { 0 }
fun String.histogram() = groupingBy { it }.eachCount().withDefault { 0 }

fun <T> List<T>.groupContiguous(): List<List<T>> {
  val groups = mutableListOf<MutableList<T>>()
  forEach { e ->
    if (e == groups.lastOrNull()?.lastOrNull()) {
      groups.last().add(e)
    } else {
      groups.add(mutableListOf(e))
    }
  }
  return groups
}

fun <T> permutationsWithReplacement(input: Set<T>, n: Int): List<List<T>> =
  if (n <= 0) listOf(emptyList())
  else input.flatMap { first ->
    permutationsWithReplacement(input, n - 1).map { rest ->
      listOf(first) + rest
    }
  }

fun <T> permutations(input: Set<T>): List<List<T>> {
  if (input.isEmpty()) return listOf(emptyList())

  val first = input.first()
  val tail = input.drop(1).toSet()

  return permutations(tail).flatMap { rest ->
    (0..rest.size).map {
      buildList {
        addAll(rest.take(it))
        add(first)
        addAll(rest.drop(it))
      }
    }
  }
}

fun <T> combinations(input: Set<T>, n: Int): Set<Set<T>> {
  if (n <= 0) return setOf(emptySet())
  if (input.isEmpty()) return emptySet()

  val first = input.take(1).toSet()
  val tail = input.drop(1).toSet()

  return combinations(tail, n - 1).map { rest -> first + rest }.toSet() + combinations(tail, n)
}

// Math
fun Int.isOdd() = this % 2 == 1
fun Long.isOdd() = this % 2 == 1L
fun Int.isEven() = !isOdd()
fun Long.isEven() = !isOdd()
fun Int.isZero() = this == 0
fun Long.isZero() = this == 0L
fun Int.isPositive() = this > 0
fun Long.isPositive() = this > 0L
fun Int.isNegative() = this < 0
fun Long.isNegative() = this < 0L
fun Int.isPositiveOrZero() = this >= 0
fun Long.isPositiveOrZero() = this >= 0L
fun Int.isNegativeOrZero() = this <= 0
fun Long.isNegativeOrZero() = this <= 0L

infix fun Int.divides(o: Int) = o % this == 0
infix fun Long.divides(o: Long) = o % this == 0L
infix fun Int.divisibleBy(o: Int) = o divides this
infix fun Long.divisibleBy(o: Long) = o divides this

infix fun Int.floorDiv(o: Int) = floor(toDouble() / o).toInt()
infix fun Long.floorDiv(o: Long) = floor(toDouble() / o).toInt()
infix fun Int.ceilDiv(o: Int) = ceil(toDouble() / o).toInt()
infix fun Long.ceilDiv(o: Long) = ceil(toDouble() / o).toInt()

infix fun Int.mod(m: Int) = ((this % m) + m) % m
infix fun Long.mod(m: Long) = ((this % m) + m) % m

// Number Theory
fun primeSieve(n: Int): List<Boolean> {
  val s = BooleanArray(n + 1) { true }
  val limit = sqrt(n.toDouble()).toInt()
  (2..limit).forEach { i ->
    if (s[i]) (i * i..n).forEach { j -> s[j] = false }
  }
  return s.toList()
}

fun primes(n: Int) = primeSieve(n).mapIndexedNotNull { i, p -> i.takeIf { p } }

// DP
inline fun <I, O> memoize(crossinline fn: (I) -> O): ((I) -> O) = with(ConcurrentHashMap<I, O>()) {
  { input -> get(input) ?: fn(input).also { output -> set(input, output) } }
}
// endregion

fun solve(p: String, q: String): Boolean {
  if (p.length != q.length)
    return false
  val m = p.zip(q).withIndex().filter { (_, v) -> v.first != v.second }.map { it.index }
  if (m.size != 2)
    return false
  val (i, j) = m
  return p[i] == q[j] && p[j] == q[i]
}

fun main() {
  val (p, q) = readLines(2)
  println(solve(p, q).yesNo())
}

[{'input': ['ab\r\nba\r\n'], 'output': ['YES\r\n']}, {'input': ['aa\r\nab\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\nza\r\n'], 'output': ['NO\r\n']}, {'input': ['vvea\r\nvvae\r\n'], 'output': ['YES\r\n']}, {'input': ['rtfabanpc\r\natfabrnpc\r\n'], 'output': ['YES\r\n']}, {'input': ['mt\r\ntm\r\n'], 'output': ['YES\r\n']}, {'input': ['qxolmbkkt\r\naovlajmlf\r\n'], 'output': ['NO\r\n']}, {'input': ['b\r\ng\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\naba\r\n'], 'output': ['NO\r\n']}, {'input': ['ba\r\na\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\nab\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\naa\r\n'], 'output': ['NO\r\n']}, {'input': ['a\r\nz\r\n'], 'output': ['NO\r\n']}, {'input': ['aabb\r\nbbaa\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nbd\r\n'], 'output': ['NO\r\n']}, {'input': ['bac\r\ndae\r\n'], 'output': ['NO\r\n']}, {'input': ['abc\r\nakl\r\n'], 'output': ['NO\r\n']}, {'input': ['cb\r\naa\r\n'], 'output': ['NO\r\n']}, {'input': ['abaab\r\naabba\r\n'], 'output': ['NO\r\n']}, {'input': ['aab\r\naaa\r\n'], 'output': ['NO\r\n']}, {'input': ['abcde\r\nedcba\r\n'], 'output': ['NO\r\n']}, {'input': ['abab\r\nbaba\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nbac\r\n'], 'output': ['NO\r\n']}, {'input': ['abcd\r\naqcb\r\n'], 'output': ['NO\r\n']}, {'input': ['abc\r\nbad\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nca\r\n'], 'output': ['NO\r\n']}, {'input': ['abc\r\nab\r\n'], 'output': ['NO\r\n']}, {'input': ['ab\r\nbae\r\n'], 'output': ['NO\r\n']}, {'input': ['aaaabcccca\r\naaaadccccb\r\n'], 'output': ['NO\r\n']}, {'input': ['acaa\r\nabca\r\n'], 'output': ['NO\r\n']}, {'input': ['aba\r\naab\r\n'], 'output': ['YES\r\n']}, {'input': ['ah\r\nla\r\n'], 'output': ['NO\r\n']}, {'input': ['aab\r\naa\r\n'], 'output': ['NO\r\n']}, {'input': ['abab\r\nabcd\r\n'], 'output': ['NO\r\n']}, {'input': ['ed\r\nab\r\n'], 'output': ['NO\r\n']}]


import java.util.Scanner

fun main() {

    val sc = Scanner(System.`in`)
    val n : Int = sc.nextInt()
    val p = IntArray(n)
    val abcde = IntArray(5)
    val count = IntArray(5)
    var total : Int = 0

    for (i in 0 until n) p[i] = sc.nextInt()
    for (i in 0..4) abcde[i] = sc.nextInt()

    for (i in 0 until n) {
        total += p[i]
        for (i in 4 downTo 0) {
            if (abcde[i] <= total) {
                count[i] += (total / abcde[i])
                total %= abcde[i]
            }
        }
    }

    for (i in 0..4) println(count[i])
    print(total)

}

Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

import java.util.Scanner

fun main() {

    val sc = Scanner(System.`in`)
    val n : Int = sc.nextInt()
    val p = IntArray(n)
    val abcde = IntArray(5)
    val count = LongArray(5)
    var total : Long = 0

    for (i in 0 until n) p[i] = sc.nextInt()
    for (i in 0..4) abcde[i] = sc.nextInt()

    for (i in 0 until n) {
        total += p[i]
        for (j in 4 downTo 0) {
            if (abcde[j] <= total) {
                count[j] += (total / abcde[j])
                total %= abcde[j]
            }
        }
    }

    for (i in 0..4) println(count[i])
    print(total)

}


import java.util.*
import kotlin.collections.*
import kotlin.math.*
import java.io.*

val INPUT = System.`in`
val read = INPUT.bufferedReader()
fun main() {

    val n = 1000001;
    var prime = Array(n+5){true}
    prime[0]=false; prime[1]=false;

    for(i in 2..n+1){
        if(prime[i]==true)
            for(j in 2*i..n+1 step i)
                prime[j]=false
    }

    var h = HashSet<Long>();
    for(i in 0..n){
        if(prime[i]==true)
            h.add(i.toLong()*i.toLong())
    }

    var s = StringTokenizer(read.readLine())
    var N = s.nextToken().toInt()
    s = StringTokenizer(read.readLine())
    for(i in 1..N){
        if(h.contains(s.nextToken().toLong()))
            println("YES")
        else
            println("NO")
    }

}

We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.

The first line contains a single positive integer, n (1≤n≤10^5), showing how many numbers are in the array. The next line contains n space-separated integers xi (1≤xi≤10^12).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier.

Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't.

The given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO".

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
    var sb: StringBuilder = StringBuilder()
    var n: Int = readLine().toInt()
    var primes: BooleanArray = BooleanArray(1000001)

    primes[0] = true
    primes[1] = true

    for (i in 2..1000000) {
        if (!primes[i]) {
            for (j in i * 2..1000000 step (i)) {
                primes[j] = true
            }
        }
    }

    fun square(n: Long): Int {
        var sqrtN = Math.sqrt(n.toDouble())
        if (sqrtN == sqrtN.toInt().toDouble()) {
            return 1;
        } else {
            return 0;
        }
    }

    var st: StringTokenizer = StringTokenizer(readLine())
    while (st.hasMoreTokens()) {
        var cur: Long = st.nextToken().toLong();
        if (cur == 4L) {
            sb.append("YES")
        } else if (cur % 2 == 0L) {
            sb.append("NO")
        } else if (!primes[Math.sqrt(cur.toDouble())
                .toInt()] && square(cur) == 1
        ) {
            sb.append("YES")
        } else {
            sb.append("NO")
        }
        sb.append('\n')
    }
    println(sb)
}


fun main() {
    val n = readLine()!!.toInt() // Read the number of problems (n)

    repeat(n) {
        val (petya, vasya, tonya) = readLine()!!.split(" ").map { it.toInt() }

        // Process the views of Petya, Vasya, and Tonya here
        // You can perform any calculations or operations needed

        // Example: Determine if the majority is sure about the solution
        if ((petya + vasya + tonya) >= 2) {
            println("1") // Majority is sure
        } else {
            println("0") // Majority is not sure
        }
    }
}

One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.

The first input line contains a single integer n (1≤n≤1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.

Print a single integer — the number of problems the friends will implement on the contest.

In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it.
In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.

fun main(args: Array<String>) {
    val n = readln().toInt()
    var count = 0
    for (i in 0 until n){
        val s = readln().split(" ").map { it.toInt() }
        if(s.sum() >= 2) count++
    }
    println(count)
}


import java.util.Scanner
fun main(){
    val input=Scanner(System.`in`)
    val n=input.nextInt()
    result(n)
    }
val result:(Int)->Unit={
    if(it==1){
        println(-1)
    }else{
        var c=0
        if(it%2!=0){
            c=1
        }
        var i=1
        while(i<=it-c-1){
            if(i!=1){
                print(" ")
            }
            if(it%2!=0&&i==it-2){
                print("${i+2} $i ${i+1}")
                break
            }
            print("${i+1} $i")
            i+=2
        }
    }
}

A permutation is a sequence of integers p1,p2,...,pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1,p2,...,pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1≤i≤n) (n is the permutation size) the following equations hold ppi=i and pi≠i. Nickolas asks you to print any perfect permutation of size n for the given n.

A single line contains a single integer n (1≤n≤100) — the permutation size.

If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1,p2,...,pn — permutation p, that is perfect. Separate printed numbers by whitespaces.

import java.util.LinkedList
import java.util.Scanner
fun main(){
    val input=Scanner(System.`in`)
    val n=input.nextInt()
    result(n)
    }
val result:(Int)->Unit={
    if(it%2!=0){
        println(-1)
    }else{
        var c=0
        if(it%2!=0){
            c=1
        }
        var i=1
        while(i<=it-c-1){
            if(i!=1){
                print(" ")
            }
            if(it%2!=0&&i==it-2){
                print("${i+2} $i ${i+1}")
                break
            }
            print("${i+1} $i")
            i+=2
        }
    }
}


fun main() {
    fun readInt() = readLine()!!.toInt()

    readLine()
    val dominoes = readLine()!!
    var count = 0
    var sol = 0
    var first = true
    var lastLeft = true
    for (c in dominoes)
        when (c) {
            '.' -> count++
            'R' -> {
                sol += count
                count = 0
                lastLeft = false
            }
            'L' -> {
                if (!first) sol += count % 2
                first = false
                count = 0
                lastLeft = true
            }
        }
    if (lastLeft) sol += count
    print(sol)
}

Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

import java.util.*

fun main() {

    val sc = Scanner(System.`in`)
    val n : Int = sc.nextInt()
    val s : CharArray = sc.next().toCharArray()
    var count = 0

    for (i in 0 until n) {
        if (s[i] == 'R') {
            for (j in (i + 1) until n) {
                if (s[j] == 'L') {
                    for (k in i..j) s[k] = 'x'
                    if ((j - i) % 2 == 0) count++
                    break
                }
            }
        } else continue
    }

    for (i in 0 until n) {
        if (s[i] == 'L') {
            for (j in 0..i) s[j] = 'x'
            break
        } else if (s[i] == '.') continue
        else break
    }

    for (i in (n - 1) downTo 0) {
        if (s[i] == 'R') {
            for (j in (n - 1) downTo i) s[j] = 'x'
            break
        } else if (s[i] == '.') continue
        else break
    }

    for (i in 0 until n)
        if (s[i] == '.')
            count++

    print(count)

}


//xXHEQR_MAENXx
//  You are not prepared!
@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")

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

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

@JvmField val _reader = INPUT.bufferedReader()
fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField var _tokenizer: StringTokenizer = StringTokenizer("")
fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}
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)

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(0x594E215C127 * 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 String.sort(): String {
    var bhgdf = toCharArray()
    bhgdf.sort()
    return String(bhgdf)
}

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 main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
    val n = readInt()
    var ar = readIntArray(n)

    var res = 1
    for (i in 0..n-1) {
        var cur = 1
        if (i > 0) for (j in i-1 downTo 0) {
            println("$j ")
            if (ar[j] <= ar[j+1]) {
                ++cur
            }
            else {
                break
            }
        }

        if (i < n) for (j in i+1..n-1) {
            if (ar[j] <= ar[j-1]) {
                ++cur
            }
            else {
                break
            }
        }
        //println("$res $cur")
        res = max(res, cur)
    }
    println(res)
}

Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

fun main(args: Array<String>) {
    val size = readLine()!!.toInt()
    val list = readLine()!!.split(" ").map { it.toInt() }.toList()

    var max = 0
    list.forEachIndexed { index, element ->
        var (right, left) = getRightAndLeft(index)

        var sumLeft = 0
        var currentLeft = 0
        var canGoLeft: Boolean = false

        if (index == 0) {
            canGoLeft = false
        } else {
            currentLeft = list[left]
            canGoLeft = leftable(left, element, currentLeft)
        }

        while (canGoLeft) {
            sumLeft++
            if (left >= 0)
                currentLeft = list[left]
            left--
            if (left == -1)
                canGoLeft = false
            else
                canGoLeft = leftable(left, currentLeft, list[left])
        }

        var sumRight = 0
        var canGoRight = false
        var currentRight = 0

        if (index == size - 1)
            canGoRight = false
        else {
            currentRight = list[right]
            canGoRight = rightable(right, size, element, currentRight)
        }

        while (canGoRight) {
            sumRight++
            if (right < size)
                currentRight = list[right]
            right++
            if (right == size)
                canGoRight = false
            else
                canGoRight = rightable(right, size, currentRight, list[right])

        }

        if (sumRight + sumLeft > max) {
            max = sumRight + sumLeft
        }
        if (max == size - 1) {
            return@forEachIndexed
        }

    }

    print(max + 1)

//
}

private fun leftable(left: Int, element: Int, item: Int) =
        (left >= 0 && element >= item)

private fun rightable(right: Int, size: Int, element: Int, item: Int) =
        (right < size && element >= item)

fun getRightAndLeft(index: Int): Pair<Int, Int> {
    return Pair(index + 1, index - 1)
}


import java.util.Scanner

fun main(args : Array<String>) {

    val reader = Scanner(System.`in`)
    var n: Int = reader.nextInt()
    var arr = IntArray(n-1)

    for (i in 0..n - 2) {
        arr[i] = reader.nextInt()
    }
    var a: Int = reader.nextInt()
    var b: Int = reader.nextInt()

    var sum = 0
    var d = b - a
    var i = 0

    while(d > 0){
        sum = sum + arr[i]
        i++
        d--
    }
    println(sum)
}

The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

import java.util.Scanner

fun main(args : Array<String>) {

    val reader = Scanner(System.`in`)
    var n: Int = reader.nextInt()
    var arr = IntArray(n-1)

    for (i in 0..n - 2) {
        arr[i] = reader.nextInt()
    }
    var a: Int = reader.nextInt()
    var b: Int = reader.nextInt()
    var sum = 0

    while(a!=b){
        sum = sum + arr[a-1]
        a++
    }
    println(sum)
}


import java.util.Scanner
fun main()
{
 var n = readLine()!!.toInt()
 var s = readLine()!!.toString()
 if(n>26)println("Yes")
 else{
 var str="abcdefghijklmnopqrstuvwxyz"
 var f=0
 for(i in 0..str.length-1)
 {
    var c=0
    for(j in 0..s.length-1)
    {
        if(s[j]==str[i])c+=1
    }
    if(c>=2)
    {
    f=1
    break
    }
 }
 if(f==1)println("Yes")
 else println("No")
 }
}

Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $$$x$$$ such that there are currently at least two puppies of color $$$x$$$ and recolor all puppies of the color $$$x$$$ into some arbitrary color $$$y$$$. Luckily, this operation can be applied multiple times (including zero).For example, if the number of puppies is $$$7$$$ and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose $$$x$$$='c' right now, because currently only one puppy has the color 'c'.Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of puppies. The second line contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters, where the $$$i$$$-th symbol denotes the $$$i$$$-th puppy's color.

If it's possible to recolor all puppies into one color, print "Yes". Otherwise print "No". Output the answer without quotation signs.

NoteIn the first example Slava can perform the following steps:   take all puppies of color 'a' (a total of two) and recolor them into 'b';  take all puppies of color 'd' (a total of two) and recolor them into 'c';  take all puppies of color 'b' (three puppies for now) and recolor them into 'c'. In the second example it's impossible to recolor any of the puppies.In the third example all the puppies' colors are the same; thus there's no need to recolor anything.

fun main() {
    val t = readLine()!!.toInt()
    val z = readLine()!!.toCharArray()
    val sett = z.toHashSet()
    if (sett.size == t && t > 1)
    {
      println("No")
    }else{
      println("Yes")
    }
  }


import java.util.*
fun main(args: Array<String>) {var reader = Scanner(System.`in`)
    var numOfChild = reader.nextInt()
    var numOfThrow = numOfChild-1
    var c=1
    var w=1
    for (i in 1..numOfThrow)
    {
        c= c+w
        if (c>=numOfChild)
        {
            c-=numOfChild
        }
        w++
        print("$c ")
    }
}

A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

import java.util.Scanner

fun main(args : Array<String>) {

    val reader = Scanner(System.`in`)
    var n: Int = reader.nextInt()
    var list: MutableList<Int> = mutableListOf()

    var c = 1
    var s = 1
    for(i in 1..n){
        c++

        if(c<=n){
            list.add(c)
        }
        else{
            list.add(c%n)
        }
        c = c + s
        s++
    }
    for(i in 0..n-2) {
        if(list[i]==0) {
            print(n)
        }
        else {
            print(list[i])
        }
        print(" ")
    }
}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

import java.io.*
import java.util.*

fun dif(a: Int, b: Int) : Int {
  val x = a - b
  return (if (x / 10 == 0) 0 else 1) + (if (x % 10 == 0) 0 else 1)
}

fun solve(start: Int, end: Int, num: Int) : Int {
  var minDif = 3
  var minv = -1
  for (i in start..end) {
    var d = dif(i, num)
    if (d < minDif) {
      minDif = d
      minv = i
    }
  }
  return minv
}

fun main(args : Array<String>) {
//  val fin = Scanner(File("a.in"))
  val fin = Scanner(System.`in`)
  val form = fin.nextInt()
  val sh = if (form == 12) 1 else 0
  val eh = if (form == 12) 12 else 23
  val sm = 0
  val em = 59
  val str = fin.next()
  val hours = str.substring(0, 2).toInt()
  val mins = str.substring(3, 5).toInt()
  print("%02d".format(solve(sh, eh, hours)))
  print(":")
  print("%02d".format(solve(sm, em, mins)))
  fin.close()
}


fun main()= repeat(readLine()!!.toInt()){ var r = readLine()!!.toInt();print(if (r % 2 == 0) (r/2) -1 else r/2) }

There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

fun main() {
    val r = System.`in`.bufferedReader()
    val s = StringBuilder()
    repeat(r.readLine()!!.toInt()){
        val n = r.readLine()!!.toInt()
        when{
            n == 1 || n ==2 -> {
                println(0)}
            else -> println((n+1)/2-1)
        }
    }
}


import java.util.Scanner

val checker: (String, Int) -> Boolean = {str, int -> str.length < int}
val diffvals: String -> Int= {word -> word.chars().distinct().count()}

fun main(args: Array<String>) {
    val inp = Scanner(System.`in`)
    var word = inp.next()
    var diffs = inp.nextInt()

    if(checker(word, diffs)) {
        println("impossible")
    } else {
        println(word.length - diffs)
    }
}

Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

fun main() {
    val input = readLine()!!
    val size = input.toCharArray().distinct().size
    val desired = readLine()!!.toInt()
    if (desired > input.length) {
        println("impossible")
    } else {
        val ans = (desired - size).coerceAtLeast(0)
        println(ans)
    }
}

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


import java.util.*

fun main() {
    val scanner = Scanner(System.`in`)
    val input = scanner.nextInt()

    val countList = MutableList(input) {n -> false}
    var result = 0

    repeat(input) {
        val nextNum = scanner.nextInt()

        if (countList[nextNum - 1]) {
            result++
        } else {
            countList[nextNum - 1] = true
        }
    }

    println(result)
}

"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

import java.util.*

fun main() {
    val scanner = Scanner(System.`in`)
    val input = scanner.nextInt()

    val countList = MutableList(input) {n -> false}
    var currentCount = 0
    var result = 0

    while (scanner.hasNext()) {
        val nextNum = scanner.nextInt()

        if (currentCount == input) {
            break
        }
        currentCount++

        if (nextNum > input) {
            result++
        } else {
            if (countList[nextNum - 1]) {
                result++
            } else {
                countList[nextNum - 1] = true
            }
        }

        if (result == input) {
            break
        } else {
            continue
        }
    }

    println(result)
}


fun main() {
    val r = System.`in`.bufferedReader()
    val s = StringBuilder()
    val n = r.readLine()!!.toInt()
    var drift = MutableList(n) {
        val (a, b) = r.readLine()!!.split(" ").map { it.toInt() }
        Pair(a, b)
    }
    var ans = 0
    while (drift.isNotEmpty()) {
        ans++
        val (x, y) = drift.removeAt(0)
        val i = drift.indexOfFirst { it.first == x || it.second == y }
        val cadidate = mutableListOf<Pair<Int, Int>>()
        var nodDone = false
        if (i != -1) {
            cadidate += drift.removeAt(i)
            nodDone = true
        }
        while (nodDone) {
            nodDone = false
            for ((x1, y1) in cadidate) {
                val ind = drift.indexOfFirst { it.first == x1 || it.second == y1 }
                if (ind != -1) {
                    nodDone = true
                    cadidate += drift.removeAt(ind)
                    break
                }
            }
        }
    }
    println(ans - 1)
}

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

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

fun main(args : Array<String>) {
    Thread { run() }.start()
}

val scanner = Scanner(System.`in`)
var n = scanner.nextInt()
val arr = Array<Array<Pair<Int, Int>>>(1000) { y -> Array<Pair<Int, Int>>(1000) { Pair(it, y) } }
var x = IntArray(1000) { -1 }
var y = IntArray(1000) { -1 }
fun get(x: Int, y: Int): Pair<Int, Int> {
    if (arr[y][x].first != x || arr[y][x].second != y)
        arr[y][x] = get(arr[y][x].first, arr[y][x].second)
    return arr[y][x]
}
fun join(x1: Int, y1: Int, x2: Int, y2: Int) {
    val root = get(x1, y1)
    arr[root.second][root.first] = get(x2, y2)
}

fun run() {

    var res = 0
    for (i in 0 until n) {
        val a = scanner.nextInt() - 1
        val b = scanner.nextInt() - 1
        if (x[b] != -1 && y[a] != -1 && get(b, x[b]) != get(y[a], a))
            res--
        if (x[b] != -1)
            join(b, a, b, x[b])
        if (y[a] != -1)
            join(b, a, y[a], a)
        if (x[b] == -1 && y[a] == -1)
            res++
        if (x[b] == -1)
            x[b] = a
        if (y[a] == -1)
            y[a] = b
    }
    println(res - 1)

}

class Scanner(s: InputStream) {
    var st: StringTokenizer? = null
    var br: BufferedReader = BufferedReader(InputStreamReader(s))
    @Throws(IOException::class)
    operator fun next(): String {
        while (st == null || !st!!.hasMoreTokens())
            st = StringTokenizer(br.readLine())
        return st!!.nextToken()
    }
    @Throws(IOException::class)
    fun nextInt(): Int {
        return Integer.parseInt(next())
    }
    @Throws(IOException::class)
    fun nextLong(): Long {
        return java.lang.Long.parseLong(next())
    }
    @Throws(IOException::class)
    fun nextLine(): String {
        return br.readLine()
    }
    @Throws(IOException::class)
    fun nextDouble(): Double {
        return java.lang.Double.parseDouble(next())
    }
    @Throws(IOException::class)
    fun ready(): Boolean {
        return br.ready()
    }
}

fun IntArray.print() {
    println(Arrays.toString(this))
}

fun Array<IntArray>.print() {
    for (i in this)
        i.print()
}


fun main() {
    val x = getInputInt()
    val y = getInputInt()
    val z = getInputInt()

    val a = getInputInt()
    val b = getInputInt()
    val c = getInputInt()

    val grapesMap = mutableMapOf(
        "green" to a,
        "purple" to b,
        "black" to c
    )

    provideAndrew(grapesMap, x)
    provideDmitri(grapesMap, y)
    provideMichal(grapesMap, z)
    if (isValidDistribution(grapesMap)) println("YES")
    else println("NO")
}

private fun getInputString() = readLine()!!
private fun getInputInt() = getInputString().toInt()

private fun provideAndrew(grapesMap: MutableMap<String, Int>, wanted: Int) {
    grapesMap["green"] = grapesMap["green"]!!.minus(wanted)
}

private fun provideDmitri(grapesMap: MutableMap<String, Int>, wanted: Int) {
    val purple = grapesMap["purple"]!!
    if(wanted <= purple) {
        grapesMap["purple"] = purple.minus(wanted)
        return
    }
    grapesMap["purple"] = 0
    grapesMap["green"] = grapesMap["green"]!!.minus(wanted - purple)
}

private fun provideMichal(grapesMap: MutableMap<String, Int>, wanted: Int) {
    grapesMap["black"] = grapesMap["black"]!!.minus(wanted)
}

private fun isValidDistribution(grapesMap: MutableMap<String, Int>) =
    grapesMap.filter { it.value >= 0 }.size == grapesMap.size

The Duck songFor simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: Andrew, Dmitry and Michal should eat at least $$$x$$$, $$$y$$$ and $$$z$$$ grapes, respectively. Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with $$$a$$$ green grapes, $$$b$$$ purple grapes and $$$c$$$ black grapes.However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?It is not required to distribute all the grapes, so it's possible that some of them will remain unused.

The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$1 \le x, y, z \le 10^5$$$) — the number of grapes Andrew, Dmitry and Michal want to eat. The second line contains three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^5$$$) — the number of green, purple and black grapes in the box.

If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".

NoteIn the first example, there is only one possible distribution:Andrew should take $$$1$$$ green grape, Dmitry should take $$$3$$$ remaining green grapes and $$$3$$$ purple grapes, and Michal will take $$$2$$$ out of $$$3$$$ available black grapes.In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(

  fun main(args:Array<String>){
    val (a, b, c) = readLine()!!.split(' ')
    var x1:Int = a.toInt()
    var y1:Int = b.toInt()
    var z1:Int = c.toInt()
    val (a1, b1, c1) = readLine()!!.split(' ')
    var x:Int = a1.toInt()
    var y:Int = b1.toInt()
    var z:Int = c1.toInt()
    var flag = 0
    if(x1 <= x && flag == 0) {x -= x1}
    else {flag = 1}

    if(y1 <= (y + x) && flag == 0)
        {
            if(y1 <= y) y -= y1
            else {
                x -= (y1 - y)
                y = 0
            }
        }
    else {flag = 1}

    if(z1 <= (x + y + z) && flag == 0) {flag = 0}
    else { flag = 1}

    if(flag == 0) {println("YES")}
    else {println("NO")}
}


import java.lang.Long.max
import java.util.*
import kotlin.collections.ArrayList

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val n = scanner.nextInt()
    val k = scanner.nextInt()
    val arr = ArrayList<Int>()
    for (i in 0..n - 1) {
        arr.add(scanner.nextInt())
    }

    val w = ArrayList<Int>()
    val o = ArrayList<Int>()
    val r = ArrayList<Int>()

    scanner.nextLine()
    val st = scanner.nextLine()

    for (i in 0..n - 1) {
        if (st.get(i) == 'W') {
            w.add(arr.get(i))
        }
        if (st.get(i) == 'O') {
            o.add(arr.get(i))
        }
        if (st.get(i) == 'R') {
            r.add(arr.get(i))
        }
    }

    Collections.sort(w, Collections.reverseOrder())
    Collections.sort(o, Collections.reverseOrder())
    Collections.sort(r, Collections.reverseOrder())

    var fl1 = false
    var fl2 = false

    var sum1: Long = 0L
    var sum2: Long = 0L

    var pos1 = 0
    var pos2 = 0

    if (o.size + w.size < k && o.size + r.size < k) {
        println(-1)
        return
    }

    if (o.size + w.size >= k) {
        while (pos1 + pos2 != k - 1) {
            if (pos1 == w.size || pos2 < o.size && w.get(pos1) < o.get(pos2)) {
                sum1 += o.get(pos2)
                pos2 += 1
                fl2 = true
            } else {
                sum1 += w.get(pos1)
                pos1 += 1
                fl1 = true
            }
        }

        if (fl1 && fl2) {
            if (pos2 == o.size || pos1 < w.size && w.get(pos1) >= o.get(pos2)) {
                sum1 += w.get(pos1)
            } else {
                sum1 += o.get(pos2)
            }
        } else if (pos2 != o.size && fl1) {
            sum1 += o.get(pos2)
            fl2 = true
        } else {
            sum1 += w.get(pos1)
            fl1 = true
        }
    }
    if (!fl1 || !fl2) {
            sum1 = -1
            }

    pos1 = 0
    pos2 = 0
    fl1 = false
    fl2 = false
    if (o.size + r.size >= k) {
        while (pos1 + pos2 != k - 1) {
            if (pos1 == r.size || pos2 < o.size && r.get(pos1) < o.get(pos2)) {
                sum2 += o.get(pos2)
                pos2 += 1
                fl2 = true
            } else {
                sum2 += r.get(pos1)
                pos1 += 1
                fl1 = true
            }
        }

        if (fl1 && fl2) {
            if (pos2 == o.size || pos1 < r.size && r.get(pos1) >= o.get(pos2)) {
                sum2 += r.get(pos1)
            } else {
                sum2 += o.get(pos2)
            }
        } else if (pos2 != o.size && fl1) {
            sum2 += o.get(pos2)
            fl2 = true
        } else {
            sum2 += r.get(pos1)
            fl1 = true
        }
    }
    if (!fl1 || !fl2) {
            sum2 = -1
            }

    println(max(sum1, sum2))
}

Arkady decided to buy roses for his girlfriend.A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy. The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose. The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O'  — orange, 'R' — red.

Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.

NoteIn the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color.

import java.io.PrintWriter
import kotlin.math.*

fun main() {
    io.apply done@ {

        val n = int
        val k = int

        val d = ints(n)
        val colors = str(n)

        val red = (0 until n).filter { colors[it] == 'R' }.map { d[it] }.toIntArray()
        val orange = (0 until n).filter { colors[it] == 'O' }.map { d[it] }.toIntArray()
        val white = (0 until n).filter { colors[it] == 'W' }.map { d[it] }.toIntArray()

        if (k < 2 || orange.isEmpty() || (red.isEmpty() && white.isEmpty())) {
            cout .. -1 .. nl
            return@done
        }

        fun compose(a: IntArray, b: IntArray): Int {
            if (a.size + b.size < k || a.isEmpty() || b.isEmpty())
                return -1
            var ia = 1
            var ib = 1
            var res = a[0] + b[0]
            repeat(k - 2) {
                if (ia == a.size)
                    res += b[ib++]
                else if (ib == b.size)
                    res += a[ia++]
                else {
                    if (a[ia] > b[ib])
                        res += a[ia++]
                    else
                        res += b[ib++]
                }
            }
            return res
        }

        red.sortDescending()
        orange.sortDescending()
        white.sortDescending()

        val ans = max(compose(red, orange), compose(white, orange))
        cout .. ans .. nl

    }.cout.flush()
}

// @formatter:off
private val io = object {
    private val `in` = System.`in`
    private fun ll(): Long {
        var x: Int; var q = false; var n = 0L; do x = `in`.read() while (x < 33); if (x == 45) { q = true; x = `in`.read() }
        do { n = n * 10 - x + 48; x = `in`.read() } while (x > 32); return if (q) n else -n
    }
    val int get() = ll().toInt(); val long get() = ll()
    fun ints(n: Int = int): IntArray { return IntArray(n) { int } }
    fun ints1(n: Int = int): IntArray { return IntArray(n) { int - 1 } }
    val cout = PrintWriter(System.out); val nl = "\n"
    private var buf = CharArray(32)
    private var bufSize = 32
    fun str(expect: Int = 32): String {
        var ix = 0
        var x: Int
        if (bufSize < expect)
            buf = CharArray(expect)
        do x = `in`.read() while (x < 33)
        do {
            if (ix == bufSize) { bufSize *= 2; buf = buf.copyOf(bufSize) }
            buf[ix++] = x.toChar()
            x = `in`.read()
        } while (x > 32)
        return java.lang.String.copyValueOf(buf, 0, ix)
    }
    operator fun PrintWriter.rangeTo(a: Int): PrintWriter { print(a); print(" "); return this }
    operator fun PrintWriter.rangeTo(a: Long): PrintWriter { print(a); print(" "); return this }
    operator fun PrintWriter.rangeTo(a: IntArray): PrintWriter { a.forEach { print(it); print(" ") }; return this }
    operator fun PrintWriter.rangeTo(a: String): PrintWriter { write(a); return this }
} // @formatter:on

/* ----------- */


fun main() {
    val n = readLine()!!
    println(oneBasedArithmetic(n, 0))
}

fun oneBasedArithmetic(string: String, count: Int): Int {
    val length = if (string[0] == '-') string.length - 1 else string.length
    val count1 = withNOnes(string, count, length)
    val count2 = withNPlus1Ones(string, count)
    return if (count1 < count2) count1 else count2
}

fun withNOnes(string: String, count: Int, length: Int): Int {
    val n = if (string[0] == '-') string.length - 1 else string.length
    val num = string.toLong()
    val nOnes = "1".repeat(n).toLong()
    return when {
//        n < length -> oneBasedArithmetic(string, count)
        n > length -> Int.MAX_VALUE
        num == 0L -> count
        num == -1L -> count + 1
        num == 1L -> count + 1
        num < 0L -> {
            val rem = (num % nOnes).toString()
            val quotient = num / nOnes
            if (quotient == 0L && rem.length == n+1){
                withNOnes((num + nOnes).toString(), count + n, n)
            }else
            oneBasedArithmetic(rem, count + (n * quotient.unaryMinus()).toInt())
        }
        else -> {
            val rem = (num % nOnes).toString()
            val quotient = num / nOnes
            if (quotient == 0L && rem.length == n){
                withNOnes((num - nOnes).toString(), count + n, n)
            }else
            oneBasedArithmetic(rem, count + (n * quotient).toInt())
        }
    }
}

fun withNPlus1Ones(string: String, count: Int): Int {
    val n = if (string[0] == '-') string.length - 1 else string.length
    val num = string.toLong()
    val nOnes = "1".repeat(n + 1).toLong()
    return when {
        num < 0L -> withNOnes((num + nOnes).toString(), count + n + 1, n)
        else -> withNOnes((nOnes - num).toString(), count + n + 1, n)
    }
}

Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.

The first line of the input contains integer n (1 ≤ n < 1015).

Print expected minimal number of digits 1.

import kotlin.math.*

fun readLn() = readLine()!! // string line
fun readInt() = readLn().toInt() // single int
fun readStrings() = readLn().split(" ") // list of strings
fun readInts() = readStrings().map { it.toInt() } // list of ints
fun readLongs() = readStrings().map { it.toLong() } // list of ints
fun readLong() = readLn().toLong() // list of strings

fun getLength(_n:Long):Int{
    var n = _n
    if (n == 0L)
        return 0
    var ret = 0
    while(n > 0L)
    {
        ret++
        n = n / 10
    }
    return ret
}

fun get1(_l:Int):Long{
    var n = _l
    if (n == 0)
        return 1
    var ret = 1L
    while(n > 1)
    {
        ret=1 + ret * 10
        n--
    }
    return ret
}

fun main() {
    val n =readLong()
    val res = getCount(n, getLength(n) + 1 )
    // println(res)
    println(get1Count(res))
}

fun get1Count(lst:List<Int>):Int
{
    var ret = 0
    for(i in 0 until lst.size)
    {
        val item = lst[i]
        ret+=(i+1)*item.absoluteValue
    }
    return ret
}

fun getCount(_n:Long, _l:Int):MutableList<Int>
{
    if (_n ==0L && _l ==0)
        return mutableListOf<Int>()

    var n =if (_n> 0)  _n  else -_n

    val l = _l

    if (l == 1)
    {
        return mutableListOf(n.toInt())
    }

    val l1 = get1(l)

    val bDigit = (n / l1).toInt()
    val tDigit = bDigit + 1

    val solb = getCount(n - l1 * bDigit, l - 1)
    val vb = get1Count(solb) + bDigit * l

    val solt = getCount(l1 * tDigit - n, l - 1)
    for (i in 0 until solt.size) {
        solt[i] = -solt[i]
    }
    val vt = get1Count(solt) + tDigit * l

    if (vb < vt)
    {
        solb.add(0)
        solb[l-1] = bDigit
        return solb
    }
    else
    {
        solt.add(0)
        solt[l-1] = tDigit
        return solt
    }

}


/**
 * Created by yakutovd on 17.03.2018.
 */

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.StringTokenizer
import java.util.TreeSet

/**
 * Created by yakutovd on 17.03.2018.
 */
fun main(args: Array<String>) {
    try {
        val out = PrintWriter(System.out)
        val br = BufferedReader(InputStreamReader(System.`in`))
        val n = Integer.parseInt(br.readLine())
        val set = TreeSet<Pair>()

        for (i in 0..(n - 1)) {
            val st = StringTokenizer(br.readLine())
            val l = Integer.parseInt(st.nextToken())
            val r = Integer.parseInt(st.nextToken())
            val pair = Pair(l, r)
            var L = l
            var R = r
            while (true) {
                val toRight = set.ceiling(pair)
                if (toRight != null && toRight.l <= r) {
                    R = Math.max(R, toRight.r)
                    set.remove(toRight)
                } else {
                    break
                }
            }
            while (true) {
                val toLeft = set.floor(pair)
                if (toLeft != null && toLeft.r >= l) {
                    L = Math.min(L, toLeft.l)
                    set.remove(toLeft)
                } else {
                    break
                }
            }
            set.add(Pair(L, R))
            out.print(set.size.toString() + " ")
        }
        out.println()
        out.close()
    } catch (ex : IOException) {
    }
}

class Pair(internal var l: Int, internal var r: Int) : Comparable<Pair> {

    override fun compareTo(o: Pair): Int {
        return if (l != o.l) {
            Integer.compare(l, o.l)
        } else Integer.compare(r, o.r)
    }
}

There is a straight line colored in white. n black segments are added on it one by one.After each segment is added, determine the number of connected components of black segments (i. e. the number of black segments in the union of the black segments). In particular, if one segment ends in a point x, and another segment starts in the point x, these two segments belong to the same connected component.

The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of segments. The i-th of the next n lines contains two integers li and ri (1 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. The segments are listed in the order they are added on the white line.

Print n integers — the number of connected components of black segments after each segment is added.

NoteIn the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that.

/**
 * Created by yakutovd on 17.03.2018.
 */

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.StringTokenizer
import java.util.TreeSet

/**
 * Created by yakutovd on 17.03.2018.
 */
fun main(args: Array<String>) {
    try {
        val out = PrintWriter(System.out)
        val br = BufferedReader(InputStreamReader(System.`in`))
        val n = Integer.parseInt(br.readLine())
        val set = TreeSet<Pair>()

        for (i in 0..(n - 1)) {
            val st = StringTokenizer(br.readLine())
            val l = Integer.parseInt(st.nextToken())
            val r = Integer.parseInt(st.nextToken())
            val pair = Pair(l, r)
            var L = l
            var R = r
            while (true) {
                val toRight = set.ceiling(pair)
                if (toRight != null && toRight.l <= r) {
                    L = Math.min(L, toRight.l)
                    R = Math.max(R, toRight.r)
                    set.remove(toRight)
                } else {
                    break
                }
            }
            while (true) {
                val toLeft = set.floor(pair)
                if (toLeft != null && toLeft.r >= l) {
                    L = Math.min(L, toLeft.l)
                    R = Math.max(R, toLeft.r)
                    set.remove(toLeft)
                } else {
                    break
                }
            }
            set.add(Pair(L, R))
            out.print(set.size.toString() + " ")
        }
        out.println()
        out.close()
    } catch (ex : IOException) {
    }
}

class Pair(internal var l: Int, internal var r: Int) : Comparable<Pair> {

    override fun compareTo(o: Pair): Int {
        return if (l != o.l) {
            Integer.compare(l, o.l)
        } else Integer.compare(r, o.r)
    }
}