kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
abdurakhmonoff__data-structures-and-algorithms-kotlin__cd9746d/src/algorithms/sorting/quick_sort/QuickSort.kt | package algorithms.sorting.quick_sort
/**
* Implementation of the quick sort algorithm for sorting a list of integers in ascending order.
*/
class QuickSort {
/**
* Sorts an array of integers in ascending order using QuickSort algorithm.
*
* @param arr the array to be sorted.
* @param low the starting index of the array.
* @param high the ending index of the array.
*/
fun quickSort(arr: IntArray, low: Int, high: Int) {
if (low < high) {
// Find partition index
val pIndex = partition(arr, low, high)
// Recursively sort elements before and after partition index
quickSort(arr, low, pIndex - 1)
quickSort(arr, pIndex + 1, high)
}
}
/**
* Partitions the array into two sub-arrays around the pivot element.
*
* @param arr the array to be partitioned.
* @param low the starting index of the array.
* @param high the ending index of the array.
* @return the index of the pivot element after partitioning.
*/
private fun partition(arr: IntArray, low: Int, high: Int): Int {
val pivot = arr[high]
var i = low - 1
// Iterate through numbers from low to high-1
for (j in low until high) {
if (arr[j] <= pivot) {
i++
// Swap arr[i] and arr[j]
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
// Place pivot at correct position in array
val temp = arr[i + 1]
arr[i + 1] = arr[high]
arr[high] = temp
// Return partition index
return i + 1
}
/**
* Prints the elements of the array.
*
* @param arr the array to be printed.
*/
fun printArray(arr: IntArray) {
for (value in arr) print("$value ")
println()
}
}
fun main() {
val numbers = intArrayOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0)
val quickSort = QuickSort()
quickSort.quickSort(numbers, 0, numbers.size - 1)
quickSort.printArray(numbers)
} | [
{
"class_path": "abdurakhmonoff__data-structures-and-algorithms-kotlin__cd9746d/algorithms/sorting/quick_sort/QuickSort.class",
"javap": "Compiled from \"QuickSort.kt\"\npublic final class algorithms.sorting.quick_sort.QuickSort {\n public algorithms.sorting.quick_sort.QuickSort();\n Code:\n 0: al... |
afranken__advent-of-code-kotlin__0140f68/2021/src/main/kotlin/com/github/afranken/aoc/Day202104.kt | package com.github.afranken.aoc
object Day202104 {
fun part1(inputs: Array<String>): Int {
val draws = inputs[0].split(',')
val boards = inputs
.drop(1)
.filter { it.isNotEmpty() }
.chunked(5)
.map {
Board.of(it.map {
it.split(" ", " ")
.filter { it.isNotBlank() } // Leading whitespace
.map { it.toInt() }
})
}
for (draw in draws) {
boards.forEach { it.markField(Integer.valueOf(draw)) }
val bingoBoard = boards.firstOrNull { it.isBingo() }
if (bingoBoard != null) {
return bingoBoard.getUnmarked().sum() * Integer.valueOf(draw)
}
}
return -1
}
fun part2(inputs: Array<String>): Int {
val draws = inputs[0].split(',')
var boards = inputs
.drop(1)
.filter { it.isNotEmpty() }
.chunked(5)
.map {
Board.of(it.map {
it.split(" ", " ")
.filter { it.isNotBlank() } // Leading whitespace
.map { it.toInt() }
})
}
for ((count, draw) in draws.withIndex()) {
boards.forEach { it.markField(Integer.valueOf(draw)) }
boards.filter { it.isBingo() }
.forEach {
// there are 100 draws. If this is not the last board, it's still the last one to win.
if (boards.size == 1 || count == 100) {
return it.getUnmarked().sum() * Integer.valueOf(draw)
}
boards = boards - it
}
}
return -1
}
data class Field(val value: Int, var marked: Boolean = false)
data class Board(val fields: List<MutableList<Field>>) {
private val widthIndices = fields[0].indices
private val heightIndices = fields.indices
companion object {
fun of(lines: List<List<Int>>): Board {
return Board(lines.map { it.map { Field(it) }.toMutableList() })
}
}
fun markField(value: Int) {
fields.forEach { it.filter { it.value == value }.forEach { it.marked = true } }
}
fun getUnmarked(): List<Int> {
return fields.flatten().filter { !it.marked }.map { it.value }
}
fun isBingo(): Boolean {
return checkColumnMarked() || checkRowMarked()
}
private fun checkRowMarked(): Boolean {
return fields.any { it.all { it.marked } }
}
private fun checkColumnMarked(): Boolean {
for (column in widthIndices) {
var columnMarked = true
for (row in heightIndices) {
if (!fields[row][column].marked) {
columnMarked = false
continue
}
}
if (columnMarked) return true
}
return false
}
}
}
| [
{
"class_path": "afranken__advent-of-code-kotlin__0140f68/com/github/afranken/aoc/Day202104$Board.class",
"javap": "Compiled from \"Day202104.kt\"\npublic final class com.github.afranken.aoc.Day202104$Board {\n public static final com.github.afranken.aoc.Day202104$Board$Companion Companion;\n\n private fi... |
afranken__advent-of-code-kotlin__0140f68/2021/src/main/kotlin/com/github/afranken/aoc/Day202106.kt | package com.github.afranken.aoc
object Day202106 {
fun part1(inputs: Array<String>): Long {
val fish = fishMap(inputs.map { Integer.valueOf(it) })
val agedFish = age(fish, 80)
return agedFish.values.sum()
}
fun part2(inputs: Array<String>): Long {
val fish = fishMap(inputs.map { Integer.valueOf(it) })
val agedFish = age(fish, 256)
return agedFish.values.sum()
}
private fun fishMap(inputs: List<Int>): MutableMap<Int, Long> {
val fish = mutableMapOf<Int, Long>()
inputs.forEach { fish.merge(it, 1, Long::plus) }
return fish
}
private fun age(fish: MutableMap<Int, Long>, days: Int): Map<Int, Long> {
repeat(days) {
val eights = fish.getOrDefault(8, 0)
val sevens = fish.getOrDefault(7, 0)
val sixes = fish.getOrDefault(6, 0)
val fives = fish.getOrDefault(5, 0)
val fours = fish.getOrDefault(4, 0)
val threes = fish.getOrDefault(3, 0)
val twos = fish.getOrDefault(2, 0)
val ones = fish.getOrDefault(1, 0)
val zeroes = fish.getOrDefault(0, 0)
//zeroes spawn new 8s
fish[8] = zeroes
fish[7] = eights
//zeroes are set to 6s after spawning, 7s degrade to 6s
fish[6] = zeroes + sevens
fish[5] = sixes
fish[4] = fives
fish[3] = fours
fish[2] = threes
fish[1] = twos
fish[0] = ones
}
return fish
}
}
| [
{
"class_path": "afranken__advent-of-code-kotlin__0140f68/com/github/afranken/aoc/Day202106.class",
"javap": "Compiled from \"Day202106.kt\"\npublic final class com.github.afranken.aoc.Day202106 {\n public static final com.github.afranken.aoc.Day202106 INSTANCE;\n\n private com.github.afranken.aoc.Day2021... |
afranken__advent-of-code-kotlin__0140f68/2021/src/main/kotlin/com/github/afranken/aoc/Day202103.kt | package com.github.afranken.aoc
import kotlin.math.pow
object Day202103 {
fun part1(inputs: Array<String>): Int {
//every input is expected to have the same size. Take inputs[0] to initialize.
val inputLength = inputs[0].length
val zeroes = IntArray(inputLength)
val ones = IntArray(inputLength)
//count up ones and zeroes
for (input in inputs) {
for (i in 0 until inputLength) {
when (input[i].digitToInt()) {
0 -> zeroes[i]++
1 -> ones[i]++
}
}
}
val gammaBinary = Array(inputLength) { "" }
val epsilonBinary = Array(inputLength) { "" }
//construct gamma and epsilon binary numbers
for (i in 0 until inputLength) {
if (zeroes[i] > ones[i]) {
gammaBinary[i] = "0"
epsilonBinary[i] = "1"
} else {
gammaBinary[i] = "1"
epsilonBinary[i] = "0"
}
}
//convert to String representing binary code, then to decimal
val gamma = toDecimal(gammaBinary.joinToString(""))
val epsilon = toDecimal(epsilonBinary.joinToString(""))
return gamma * epsilon
}
fun part2(inputs: Array<String>): Int {
//all inputs are expected to have the same length
val inputLength = inputs[0].length
//iterate over initial list
//split list into 1s and 0s for the first bit position
val splitted = splitListByBit(inputs, 0)
var oxygenBinary = if (splitted[1].size >= splitted[0].size) splitted[1] else splitted[0]
var co2Binary = if (splitted[0].size <= splitted[1].size) splitted[0] else splitted[1]
//process both lists: larger list for oxygen, smaller list for co2. Given equal size,
// process 1s for oxygen.
for (i in 1 until inputLength) {
if (oxygenBinary.size > 1) {
//oxygen: go through list for every bit position in 1 until length, always keep the larger list
val oxygenSplit = splitListByBit(oxygenBinary, i)
oxygenBinary = findNext(oxygenSplit[1], oxygenSplit[0], true)
}
if (co2Binary.size > 1) {
//co2: go through list for every bit position in 1 until length, always keep smaller list.
val co2Split = splitListByBit(co2Binary, i)
co2Binary = findNext(co2Split[1], co2Split[0], false)
}
}
//convert to String representing binary code, then to decimal
val oxygen = toDecimal(oxygenBinary.joinToString(""))
val co2 = toDecimal(co2Binary.joinToString(""))
return oxygen * co2
}
private fun findNext(ones: Array<String>, zeroes: Array<String>, oxygen: Boolean): Array<String> {
return if (oxygen) {
if (ones.size >= zeroes.size) { //oxygen prefers 1s over 0s when sizes are equal
ones
} else {
zeroes
}
} else {
if (zeroes.size <= ones.size) { //co2 prefers 0s over 1s when sizes are equal
zeroes
} else {
ones
}
}
}
private fun splitListByBit(inputs: Array<String>, position: Int): Array<Array<String>> {
val ones = arrayListOf<String>()
val zeroes = arrayListOf<String>()
for (input in inputs) {
val c = input[position].toString()
when (c) {
"0" -> zeroes.add(input)
"1" -> ones.add(input)
}
}
//returns zeroes array with index 0 and ones array with index 1.
return arrayOf(zeroes.toTypedArray(), ones.toTypedArray())
}
private fun toDecimal(binaryNumber: String): Int {
var sum = 0
binaryNumber.reversed().forEachIndexed { k, v ->
sum += v.toString().toInt() * 2.0.pow(k.toDouble()).toInt()
}
return sum
}
}
| [
{
"class_path": "afranken__advent-of-code-kotlin__0140f68/com/github/afranken/aoc/Day202103.class",
"javap": "Compiled from \"Day202103.kt\"\npublic final class com.github.afranken.aoc.Day202103 {\n public static final com.github.afranken.aoc.Day202103 INSTANCE;\n\n private com.github.afranken.aoc.Day2021... |
afranken__advent-of-code-kotlin__0140f68/2021/src/main/kotlin/com/github/afranken/aoc/Day202105.kt | package com.github.afranken.aoc
object Day202105 {
fun part1(inputs: Array<String>): Int {
val coordinates = getCoordinates(inputs)
val matrix = createMatrix(coordinates)
coordinates.forEach {
val from = Pair(it[0], it[1])
val to = Pair(it[2], it[3])
mark(matrix, from, to)
}
var count = 0
matrix.forEach { it.forEach { if (it >= 2) count++ } }
return count
}
fun part2(inputs: Array<String>): Int {
val coordinates = getCoordinates(inputs)
val matrix = createMatrix(coordinates)
coordinates.forEach {
val from = Pair(it[0], it[1])
val to = Pair(it[2], it[3])
mark(matrix, from, to, true)
}
var count = 0
matrix.forEach { it.forEach { if (it >= 2) count++ } }
return count
}
data class Pair(val x: Int, val y: Int)
private fun createMatrix(coordinates: List<List<Int>>): Array<IntArray> {
val size = coordinates[0][0].toString().length
var maxSizeString = ""
for (i in 0 until size) {
maxSizeString += "9"
}
val maxSize = Integer.valueOf(maxSizeString) + 1 //9->10, 99->100, 999->1000
return Array(maxSize) { IntArray(maxSize) { 0 } } //maxSize*maxSize array with '0's
}
private fun sort(from: Pair, to: Pair): List<Pair> {
return if (from.x < to.x || from.x == to.x && from.y < to.y) {
listOf(from, to)
} else {
listOf(to, from)
}
}
private fun mark(
matrix: Array<IntArray>,
from: Pair, to: Pair,
diagonals: Boolean = false
) {
val (lower, higher) = sort(from, to)
if (lower.x == higher.x) {
//vertical line.
(lower.y..higher.y).forEach {
matrix[it][lower.x]++
}
} else if (lower.y == higher.y) {
//horizontal line.
(lower.x..higher.x).forEach {
matrix[lower.y][it]++
}
} else if (diagonals) {
//diagonal line
val deltaX = higher.x - lower.x
val deltaY = higher.y - lower.y
val direction = when {
deltaY > 0 -> 1
deltaY < 0 -> -1
else -> 0
}
(0..deltaX).forEach { delta ->
matrix[lower.y + direction * delta][lower.x + delta]++
}
}
}
private fun getCoordinates(inputs: Array<String>): List<List<Int>> {
return inputs.map { it.split(",", " -> ") }.map { it.map { Integer.valueOf(it) } }
}
}
| [
{
"class_path": "afranken__advent-of-code-kotlin__0140f68/com/github/afranken/aoc/Day202105.class",
"javap": "Compiled from \"Day202105.kt\"\npublic final class com.github.afranken.aoc.Day202105 {\n public static final com.github.afranken.aoc.Day202105 INSTANCE;\n\n private com.github.afranken.aoc.Day2021... |
afranken__advent-of-code-kotlin__0140f68/2021/src/main/kotlin/com/github/afranken/aoc/Day202108.kt | package com.github.afranken.aoc
object Day202108 {
fun part1(inputs: Array<String>): Int {
val input = convert(inputs)
var count = 0
input.forEach {
it.second.forEach {
when (it.length) {
2 -> count++ // 1
4 -> count++ // 4
3 -> count++ // 7
7 -> count++ // 8
}
}
}
return count
}
fun part2(inputs: Array<String>): Int {
val input = convert(inputs)
return input.sumOf { (input, output) ->
randomConfig(input, output)
}
}
/**
* Took this from Sebastian's solution after many tries of implementing this myself.
* Kudos!
*
* https://github.com/SebastianAigner
*/
private val segmentsToDigits = mapOf(
setOf(0, 1, 2, 4, 5, 6) to 0,
setOf(2, 5) to 1,
setOf(0, 2, 3, 4, 6) to 2,
setOf(0, 2, 3, 5, 6) to 3,
setOf(1, 2, 3, 5) to 4,
setOf(0, 1, 3, 5, 6) to 5,
setOf(0, 1, 3, 4, 5, 6) to 6,
setOf(0, 2, 5) to 7,
setOf(0, 1, 2, 3, 4, 5, 6) to 8,
setOf(0, 1, 2, 3, 5, 6) to 9
)
private fun randomConfig(words: List<String>, expectedNumbers: List<String>): Int {
val inputCables = 0..6
val inputChars = 'a'..'g'
fun getMapping(): Map<Char, Int> {
permute@ while (true) {
val perm = inputChars.zip(inputCables.shuffled()).toMap()
for (word in words) {
val mapped = word.map { perm[it]!! }.toSet()
val isValidDigit = segmentsToDigits.containsKey(mapped)
if (!isValidDigit) continue@permute
}
return perm
}
}
val mapping = getMapping()
val num = expectedNumbers.joinToString("") { digit ->
val segments = digit.map { mapping[it]!! }.toSet()
val dig = segmentsToDigits[segments]!!
"$dig"
}
return num.toInt()
}
private fun convert(inputs: Array<String>): List<Pair<List<String>, List<String>>> {
return inputs.map{
val (part1, part2) = it.split(" | ")
val signals = part1.split(" ")
val digits = part2.split(" ")
Pair(signals, digits)
}
}
}
| [
{
"class_path": "afranken__advent-of-code-kotlin__0140f68/com/github/afranken/aoc/Day202108.class",
"javap": "Compiled from \"Day202108.kt\"\npublic final class com.github.afranken.aoc.Day202108 {\n public static final com.github.afranken.aoc.Day202108 INSTANCE;\n\n private static final java.util.Map<java... |
somei-san__atcoder-kotline__43ea45f/src/lib/lib.kt | package lib
import java.util.*
// 約数のList
fun divisor(value: Long): List<Long> {
val max = Math.sqrt(value.toDouble()).toLong()
return (1..max)
.filter { value % it == 0L }
.map { listOf(it, value / it) }
.flatten()
.sorted()
}
// 範囲内の素数を取得
// fromだけ指定すると戻り値の個数で素数判定ができる
fun prime(from: Long, to: Long = from): List<Long> {
return (from..to).filter { i ->
val max = Math.sqrt(i.toDouble()).toLong()
(2..max).all { j -> i % j != 0L }
}
}
// 渡された値が素数か判定
fun isPrime(source: Int): Boolean {
return prime(source.toLong()).any()
}
// 素因数分解
fun decom(value: Long): List<Long> {
if (value == 1L) return listOf(1)
val max = Math.sqrt(value.toDouble()).toLong()
return prime(2, max).filter { value % it == 0L }
}
// 最大公約数
fun gcd(a: Long, b: Long): Long {
return if (a % b == 0L) b else gcd(b, a % b)
}
// 文字列を入れ替え
fun swap(base: String, a: String, b: String): String {
return base.map {
when (it) {
a.toCharArray()[0] -> b
b.toCharArray()[0] -> a
else -> it.toString()
}
}.joinToString()
}
/**
* リストをスタックに変換する
* @param list リスト
* @return スタック
*/
fun listToStack(list: List<Int>): Stack<Int> {
// スタック
val stack = Stack<Int>()
for (e in list) {
stack.push(e)
}
return stack
}
/**
* ユークリッドの互除法を用いて、最大公約数を導出する
* @param list 最大公約数を求める対象となる数が格納されたリスト
* @return 最大公約数
*/
fun gcd(list: List<Int>): Int {
// 最大公約数を求める対象となる数が格納されたスタック
val stack = listToStack(list)
// ユークリッドの互除法を用いて、最大公約数を導出する
// (最終的にスタック内に1つだけ数が残り、それが最大公約数となる)
while (1 < stack.size) {
// スタックから2つの数をpop
val pops = (0 until 2).map {
stack.pop()
}
// スタックからpopした2つの数のうち、小さい方の数のインデックス
val minIndex = if (pops[1] < pops[0]) {
1
} else {
0
}
// スタックからpopした2つの数のうち、小さい方の数をpush
stack.push(pops[minIndex])
// スタックからpopした2つの数の剰余
val r = pops[(minIndex + 1) % 2] % pops[minIndex]
// スタックからpopした2つの数に剰余があるならば、それをpush
if (0 < r) {
stack.push(r)
}
}
// 最大公約数を返す
return stack.pop()
}
/**
* 最小公倍数を導出する
* @param list 最小公倍数を求める対象となる数が格納されたリスト
* @return 最小公倍数
*/
fun lcm(list: List<Int>): Int {
// 最大公約数を求める対象となる数が格納されたスタック
val stack = listToStack(list)
// 最小公倍数を導出する
// (最終的にスタック内に1つだけ数が残り、それが最小公倍数となる)
while (1 < stack.size) {
// スタックから2つの数をpop
val pops = (0 until 2).map {
stack.pop()
}
// スタックからpopした2つの数の最小公倍数をpush
stack.push(pops[0] * pops[1] / gcd(pops))
}
// 最小公倍数を返す
return stack.pop()
}
| [
{
"class_path": "somei-san__atcoder-kotline__43ea45f/lib/LibKt.class",
"javap": "Compiled from \"lib.kt\"\npublic final class lib.LibKt {\n public static final java.util.List<java.lang.Long> divisor(long);\n Code:\n 0: lload_0\n 1: l2d\n 2: invokestatic #14 // Method j... |
sollecitom__chassis__e4e3403/logger/core/src/main/kotlin/org/sollecitom/chassis/logger/core/implementation/datastructure/Trie.kt | package org.sollecitom.chassis.logger.core.implementation.datastructure
internal interface Trie {
/**
* Returns the word in the trie with the longest prefix in common to the given word.
*/
fun searchLongestPrefixWord(word: String): String
/**
* Returns the longest prefix in the trie common to the word.
*/
fun searchLongestPrefix(word: String): String
/**
* Returns if the word is in the trie.
*/
fun search(word: String): Boolean
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
fun searchWithPrefix(prefix: String): Boolean
interface Mutable : Trie {
/**
* Inserts a word into the trie.
*/
fun insert(word: String)
}
}
internal fun trieOf(vararg words: String): Trie = TrieNodeTree().apply { words.forEach { insert(it) } }
internal fun mutableTrieOf(vararg words: String): Trie.Mutable = TrieNodeTree().apply { words.forEach { insert(it) } }
internal fun mutableTrieOf(words: Iterable<String>): Trie.Mutable = TrieNodeTree().apply { words.forEach { insert(it) } }
private class TrieNodeTree : Trie.Mutable {
private val root: TrieNode = TrieNode()
override fun insert(word: String) {
var node: TrieNode = root
for (element in word) {
if (!node.containsKey(element)) {
node.put(element, TrieNode())
}
node = node[element]!!
}
node.setEnd()
}
override fun searchLongestPrefixWord(word: String): String {
var node = root
val prefixes = mutableListOf<String>()
val currentPrefix = StringBuilder()
for (element in word) {
if (node.containsKey(element)) {
if (node.isEnd) {
prefixes += currentPrefix.toString()
}
currentPrefix.append(element)
node = node[element]!!
} else {
if (node.isEnd) {
prefixes += currentPrefix.toString()
}
return prefixes.maxByOrNull(String::length) ?: ""
}
}
return ""
}
override fun searchLongestPrefix(word: String): String {
var node = root
val currentPrefix = StringBuilder()
for (element in word) {
if (node.containsKey(element) && node.links.size == 1) {
currentPrefix.append(element)
node = node[element]!!
} else {
return currentPrefix.toString()
}
}
return ""
}
override fun search(word: String): Boolean {
val node = searchPrefix(word)
return node != null && node.isEnd
}
override fun searchWithPrefix(prefix: String): Boolean {
val node = searchPrefix(prefix)
return node != null
}
private fun searchPrefix(word: String): TrieNode? {
var node: TrieNode? = root
for (element in word) {
node = if (node!!.containsKey(element)) {
node[element]
} else {
return null
}
}
return node
}
}
private class TrieNode private constructor(val links: MutableMap<Char, TrieNode> = mutableMapOf(), isEnd: Boolean = false) {
constructor() : this(mutableMapOf(), false)
var isEnd = isEnd
private set
fun containsKey(ch: Char): Boolean = links[ch] != null
operator fun get(ch: Char): TrieNode? = links[ch]
fun put(ch: Char, node: TrieNode) {
links[ch] = node
}
fun setEnd() {
isEnd = true
}
fun clone(): TrieNode = TrieNode(links.mapValues { it.value.clone() }.toMutableMap(), isEnd)
} | [
{
"class_path": "sollecitom__chassis__e4e3403/org/sollecitom/chassis/logger/core/implementation/datastructure/Trie$Mutable.class",
"javap": "Compiled from \"Trie.kt\"\npublic interface org.sollecitom.chassis.logger.core.implementation.datastructure.Trie$Mutable extends org.sollecitom.chassis.logger.core.imp... |
mdenburger__aoc-2021__e890eec/src/main/kotlin/day07/Day07.kt | package day07
import java.io.File
import kotlin.math.abs
import kotlin.math.min
fun main() {
println("Answer 1: " + minimumFuel(::constantCost))
println("Answer 2: " + minimumFuel(::increasingCost))
}
fun minimumFuel(cost: (positions: List<Int>, position: Int) -> Int): Int {
val positions = File("src/main/kotlin/day07/day07-input.txt").readText().split(",").map { it.toInt() }
val min = positions.minOrNull()!!
val max = positions.maxOrNull()!!
return (min..max).fold(Int.MAX_VALUE) { minimum, position ->
min(cost(positions, position), minimum)
}
}
fun constantCost(positions: List<Int>, position: Int): Int =
positions.sumOf { abs(it - position) }
fun increasingCost(positions: List<Int>, position: Int): Int =
positions.sumOf {
val distance = abs(it - position)
(distance * (distance + 1)) shr 1 // sum of integers 1..N = N * (N - 1) / 2
}
| [
{
"class_path": "mdenburger__aoc-2021__e890eec/day07/Day07Kt.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class day07.Day07Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/lang/StringBuilder\n 3: dup\n 4: invokespecial #... |
mdenburger__aoc-2021__e890eec/src/main/kotlin/day04/Day04.kt | package day04
import java.io.File
fun main() {
val lines = File("src/main/kotlin/day04/day04-input.txt").readLines().toMutableList()
val numbers = lines.removeAt(0).split(",").map { it.toInt() }
val boards = mutableListOf<Board>()
while (lines.isNotEmpty()) {
boards.add(parseBoard(lines))
}
part1(numbers.toMutableList(), boards.toMutableList())
part2(numbers.toMutableList(), boards.toMutableList())
}
fun parseBoard(lines: MutableList<String>): Board {
lines.removeFirst() // empty line
val numbers = mutableListOf<Int>()
repeat(5) {
val row = lines.removeFirst().split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
numbers += row
}
return Board(numbers)
}
fun part1(numbers: MutableList<Int>, boards: List<Board>) {
var drawn: Int
var winner: Board?
do {
drawn = numbers.removeFirst()
boards.forEach { it.mark(drawn) }
winner = boards.find { it.wins() }
} while (winner == null)
println(winner.score() * drawn)
}
fun part2(numbers: MutableList<Int>, boards: MutableList<Board>) {
var drawn: Int
var lastWinner: Board? = null
do {
drawn = numbers.removeFirst()
boards.forEach { it.mark(drawn) }
val winners = boards.filter { it.wins() }
if (winners.isNotEmpty()) {
boards.removeAll(winners)
lastWinner = winners.first()
}
} while (boards.isNotEmpty())
println(lastWinner!!.score() * drawn)
}
class Board(numbers: List<Int>) {
private val numbers = numbers.map { BoardNumber(it) }
fun mark(number: Int) {
numbers.find { it.value == number }?.mark()
}
fun wins(): Boolean = hasWinningRow() || hasWinningColumn()
private fun hasWinningRow(): Boolean =
numbers.chunked(5).any { row -> row.all { it.marked } }
private fun hasWinningColumn(): Boolean =
(0..4).any { col ->
(0..4).all { row ->
numbers[col + (row * 5)].marked
}
}
fun score(): Int =
numbers.filter { !it.marked }.sumOf { it.value }
}
class BoardNumber(val value: Int) {
var marked = false
fun mark() {
marked = true
}
}
| [
{
"class_path": "mdenburger__aoc-2021__e890eec/day04/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
mdenburger__aoc-2021__e890eec/src/main/kotlin/day05/Day05.kt | package day05
import java.io.File
fun main() {
val lines: List<Line> = File("src/main/kotlin/day05/day05-input.txt")
.readLines()
.map { it.split(" -> ") }
.map { Line(it.first().asPoint(), it.last().asPoint()) }
println("Part 1: " + countOverlappingPoints(lines.filter { it.isHorizontal() || it.isVertical() }))
println("Part 2: " + countOverlappingPoints(lines))
}
fun countOverlappingPoints(lines: List<Line>): Int {
val grid = mutableMapOf<Point, Int>()
lines.forEach { line ->
line.points().forEach { point ->
grid.compute(point) { _, value ->
if (value == null) 1 else value + 1
}
}
}
return grid.filter { it.value >= 2 }.count()
}
fun String.asPoint(): Point =
split(",").map { it.toInt() }.let { Point(it.first(), it.last()) }
data class Point(val x: Int, val y: Int)
data class Line(val first: Point, val last: Point) {
fun isHorizontal(): Boolean = first.x == last.x
fun isVertical(): Boolean = first.y == last.y
fun points(): Sequence<Point> {
val dx = (last.x - first.x).coerceIn(-1, 1)
val dy = (last.y - first.y).coerceIn(-1, 1)
return sequence {
var point = first
yield(point)
while (point != last) {
point = Point(point.x + dx, point.y + dy)
yield(point)
}
}
}
}
| [
{
"class_path": "mdenburger__aoc-2021__e890eec/day05/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class day05.Day05Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
chimbersaw__debtislav__be24597/src/main/kotlin/com/chimber/debtislav/util/Graph.kt | package com.chimber.debtislav.util
data class Edge<T>(val a: T, val b: T, var weight: Int)
class Graph<T>(edgesList: List<Edge<T>>) {
val edges: MutableList<Edge<T>>
private var start: T? = null
init {
val edgeMap = HashMap<Pair<T, T>, Int>()
for (edge in edgesList) {
edgeMap.compute(edge.a to edge.b) { _, v -> edge.weight + (v ?: 0) }
}
edges = edgeMap.map { Edge(it.key.first, it.key.second, it.value) }.toMutableList()
}
private fun dfs(v: T, g: Map<T, List<Edge<T>>>, used: MutableMap<T, Int>): MutableList<Edge<T>>? {
used[v] = 1
val outEdges = g[v] ?: run {
used[v] = 2
return null
}
for (edge in outEdges) {
val x = edge.b
if (used[x] == 0) {
val cycle = dfs(x, g, used)
cycle?.let {
if (start == null) return it
else if (start == v) start = null
it.add(edge)
return it
}
} else if (used[x] == 1) {
start = x
return mutableListOf(edge)
}
}
used[v] = 2
return null
}
private fun findCycle(): List<Edge<T>> {
val g = mutableMapOf<T, MutableList<Edge<T>>>()
for (edge in edges) {
if (!g.contains(edge.a)) {
g[edge.a] = mutableListOf()
}
g[edge.a]?.add(edge)
}
val vertices = edges.map { listOf(it.a, it.b) }.flatten().distinct()
val used = vertices.associateWith { 0 }.toMutableMap()
start = null
for (v in vertices) {
if (used[v] == 0) {
val cycle = dfs(v, g, used)
if (cycle != null) {
return cycle.reversed()
}
}
}
return emptyList()
}
private fun reduceCycle(): Boolean {
val cycle = findCycle()
val minWeight = cycle.minByOrNull { it.weight }?.weight ?: return false
val edgesToRemove = mutableListOf<Edge<T>>()
for (edge in cycle) {
edge.weight -= minWeight
if (edge.weight == 0) {
edgesToRemove.add(edge)
}
}
edges.removeAll(edgesToRemove)
return true
}
fun reduceAllCycles() {
var finished = false
while (!finished) {
finished = !reduceCycle()
}
}
}
| [
{
"class_path": "chimbersaw__debtislav__be24597/com/chimber/debtislav/util/Graph.class",
"javap": "Compiled from \"Graph.kt\"\npublic final class com.chimber.debtislav.util.Graph<T> {\n private final java.util.List<com.chimber.debtislav.util.Edge<T>> edges;\n\n private T start;\n\n public com.chimber.deb... |
NyCodeGHG__regenbogen-ice__65738ee/bot/src/main/kotlin/util/DamerauLevenshtein.kt | package dev.nycode.regenbogenice.util
import kotlin.math.min
/**
* Calculates the string distance between source and target strings using
* the Damerau-Levenshtein algorithm. The distance is case-sensitive.
*
* @param source The source String.
* @param target The target String.
* @return The distance between source and target strings.
*/
fun calculateDistance(source: CharSequence, target: CharSequence): Int {
val sourceLength = source.length
val targetLength = target.length
if (sourceLength == 0) return targetLength
if (targetLength == 0) return sourceLength
val dist = Array(sourceLength + 1) { IntArray(targetLength + 1) }
for (i in 0 until sourceLength + 1) {
dist[i][0] = i
}
for (j in 0 until targetLength + 1) {
dist[0][j] = j
}
for (i in 1 until sourceLength + 1) {
for (j in 1 until targetLength + 1) {
val cost = if (source[i - 1] == target[j - 1]) 0 else 1
dist[i][j] = min(
min(dist[i - 1][j] + 1, dist[i][j - 1] + 1),
dist[i - 1][j - 1] + cost
)
if (i > 1 && j > 1 && source[i - 1] == target[j - 2] && source[i - 2] == target[j - 1]) {
dist[i][j] = min(dist[i][j], dist[i - 2][j - 2] + cost)
}
}
}
return dist[sourceLength][targetLength]
}
inline fun <T> Collection<T>.minByDistanceOrNull(
text: CharSequence,
toString: (T) -> CharSequence = { it.toString() }
) =
minByOrNull { calculateDistance(text, toString(it)) }
| [
{
"class_path": "NyCodeGHG__regenbogen-ice__65738ee/dev/nycode/regenbogenice/util/DamerauLevenshteinKt$minByDistanceOrNull$1.class",
"javap": "Compiled from \"DamerauLevenshtein.kt\"\npublic final class dev.nycode.regenbogenice.util.DamerauLevenshteinKt$minByDistanceOrNull$1 implements kotlin.jvm.functions.... |
woody-lam__git-training-rebasing__c9c8885/src/main/kotlin/com/gitTraining/Fibbonaci.kt | package com.gitTraining
fun computeFibbonaciNumber(position: Int?, recursion: Boolean = false): Int {
if (recursion) return recursiveFibbonachi(position!!)
var notNullPosition = position
if (notNullPosition == null) {
notNullPosition = 1
}
if (position == 0) return 0
if (position != null) {
if (position < 0) {
return computeNegativeFibbonachi(position)
}
}
if (notNullPosition <= 2) return 1
if (position == 1 || position == 2) return 1
var smallFibbonachiNumber = 1
var largeFibbonachiNumber = 1
var currentPosition = 2
while (currentPosition < position!!) {
val nextFibbonachiNumber = smallFibbonachiNumber + largeFibbonachiNumber
smallFibbonachiNumber = largeFibbonachiNumber
largeFibbonachiNumber = nextFibbonachiNumber
currentPosition ++
}
return largeFibbonachiNumber
}
fun computeFibbonachiArray(start: Int, end: Int, efficient: Boolean = false): List<Int> {
if (!efficient) return (start..end).map { computeFibbonaciNumber(it) }
if (start > end) return listOf()
if (start == end) return listOf(computeFibbonaciNumber(start))
val output = mutableListOf(computeFibbonaciNumber(start), computeFibbonaciNumber(start + 1))
(2..(end - start)).forEach { output.add(output[it - 2] + output[it - 1]) }
return output
}
fun recursiveFibbonachi(previous: Int, current: Int, stepsLeft: Int): Int {
if (stepsLeft < 0) return 1
return when (stepsLeft) {
0 -> current
else -> recursiveFibbonachi(current, previous + current, stepsLeft - 1)
}
}
fun computeNegativeFibbonachi(position:Int): Int {
if (position >= 0) throw Exception("potition must be smaller than zero!")
val resultIsNegative = position % 2 == 0
val absoluteResult = computeFibbonaciNumber(-position)
return if (resultIsNegative) (absoluteResult * -1) else absoluteResult
}
fun recursiveFibbonachi(initialPosition: Int, left: Int = 0, right: Int = 1, position: Int = initialPosition): Int {
if (initialPosition == 0) return 0
if (position == 0) return left
if (initialPosition > 0) {
return recursiveFibbonachi(initialPosition, right, left + right, position - 1)
} else {
return recursiveFibbonachi(initialPosition, right - left, left, position + 1)
}
}
| [
{
"class_path": "woody-lam__git-training-rebasing__c9c8885/com/gitTraining/FibbonaciKt.class",
"javap": "Compiled from \"Fibbonaci.kt\"\npublic final class com.gitTraining.FibbonaciKt {\n public static final int computeFibbonaciNumber(java.lang.Integer, boolean);\n Code:\n 0: iload_1\n 1: if... |
BobString__kotlin-exercises__a3ef283/src/com/talkspace/exercises/sum3.kt | package com.talkspace.exercises
// Write a function that takes as its arguments a sorted array of unique integers, `intArray`, and an integer, `int`, and returns 3 integers from `intArray` that sum up to `int`.
fun main(args: Array<String>) {
println(threeSum(listOf(-1, 2, 3, 4, 5, 7, 8, 12), 6)) // [4, 3, -1]
println(twoSum(listOf(-1, 2, 3, 4, 5, 7, 8, 12), 6)) // [4, 2]
println(twoSum(listOf(-1, 2, 3, 4, 5, 7, 8, 12), 20)) // [12, 8]
}
fun threeSum(ints: List<Int>, total: Int): List<Int> {
for (integer in ints) {
val mutableTemp = ints.toMutableList()
mutableTemp.remove(integer)
val res = twoSum(mutableTemp, total - integer)
if (res.isNotEmpty()) {
val mutableRes = res.toMutableList()
mutableRes.add(integer)
return mutableRes
}
}
return listOf()
}
fun twoSum(ints: List<Int>, total: Int): List<Int> {
val hash = mutableMapOf<Int, Int>()
for (integer in ints) {
val matchingSolution = total - integer
if (hash.containsKey(matchingSolution)) {
return listOf(integer, matchingSolution)
} else {
hash[integer] = matchingSolution
}
}
return listOf()
}
| [
{
"class_path": "BobString__kotlin-exercises__a3ef283/com/talkspace/exercises/Sum3Kt.class",
"javap": "Compiled from \"sum3.kt\"\npublic final class com.talkspace.exercises.Sum3Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
cgnik__euler__fe70459/src/main/kotlin/com/zer0rez/euler/util/Util.kt | package com.zer0rez.euler.util
import kotlin.math.sqrt
fun Int.isDivisibleBy(i: Int): Boolean = this % i == 0
fun Int.isDivisibleByAll(i: IntArray): Boolean = i.all { this.isDivisibleBy(it) }
fun Long.isDivisibleBy(i: Long): Boolean = this % i == 0L
fun Long.isDivisibleByAny(i: Collection<Long>): Boolean = i.any { this.isDivisibleBy(it) }
fun Int.isPalindrome(): Boolean {
if (this < 10) return false;
val ns = this.toString()
val end = ns.length - 1
for (i in 0..(ns.length / 2)) {
if (i >= end) break
if (ns[i] != ns[end - i]) return false
}
return true
}
fun IntArray.swapin(arrow: Int): Int {
this[0] = this[1]
this[1] = arrow
return this[1]
}
fun fibonacci(quit: (Int) -> Boolean): IntArray {
var values = ArrayList<Int>()
values.add(1)
values.add(1)
while (!quit(values.last())) {
values.add(values[values.count() - 1] + values[values.count() - 2])
}
values.remove(values.last())
return values.toIntArray()
}
fun Long.factorize(): Sequence<Long> {
var target = this
var current = sqrt(target.toDouble()).toLong()
return sequence {
while (current % 2 == 0L) current /= 2
while (current > 0 && current < target) {
if (target % current == 0L) {
yield(current)
target /= current
}
current -= 2
}
}
}
fun LongArray.productSeries(size: Int) = IntRange(0, this.count() - size).map { i ->
Pair(this.slice(i until i + size).reduce { t: Long, x: Long -> x * t }, this.slice(i until i + size))
}
| [
{
"class_path": "cgnik__euler__fe70459/com/zer0rez/euler/util/UtilKt.class",
"javap": "Compiled from \"Util.kt\"\npublic final class com.zer0rez.euler.util.UtilKt {\n public static final boolean isDivisibleBy(int, int);\n Code:\n 0: iload_0\n 1: iload_1\n 2: irem\n 3: ifne ... |
zys0909__CodeLabs__869c7c2/src/com/leecode/array/Code1.kt | package com.leecode.array
/**
* 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
如何在一个1到100的整数数组中找到丢失的数字? google, Amazon,tencent
示例 1:
输入: [0,1,3]
输出: 2
示例 2:
输入: [0,1,2]
输出: 3
示例 3:
输入: [0,1,2,3,4,5,6,7,9]
输出: 8
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof
*/
/**
*
* 直接遍历
*/
fun missingNumber1(nums: IntArray): Int {
var result: Int = 0
for (i in nums) {
if (i != result) {
break
}
result++
}
return result
}
/**
* 二手分查找法
*/
fun missingNumber2(nums: IntArray): Int {
var start = 0
var end = nums.size - 1
if (nums[end] == end) {
return end + 1
}
while (start < end) {
val mid = (start + end) / 2
if (nums[mid] != mid) {
end = mid
} else {
start = mid + 1
}
}
return start
} | [
{
"class_path": "zys0909__CodeLabs__869c7c2/com/leecode/array/Code1Kt.class",
"javap": "Compiled from \"Code1.kt\"\npublic final class com.leecode.array.Code1Kt {\n public static final int missingNumber1(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String nums\n ... |
zys0909__CodeLabs__869c7c2/src/com/leecode/array/Code2.kt | package com.leecode.array
/**
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:2 <= n <= 100000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
*/
/**
* 用一个容器装已经确定的数
*/
fun findRepeatNumber1(nums: IntArray): Int {
val map = mutableSetOf<Int>()
for (i in nums) {
if (map.contains(i)) {
return i
} else {
map.add(i)
}
}
return -1
}
/**
* 先排序,再判断相邻的数是否相等
*/
fun findRepeatNumber2(nums: IntArray): Int {
nums.sort()
for (i in 1 until nums.size) {
if (nums[i] == nums[i - 1]) {
return nums[i]
}
}
return -1
}
/**
* 所有数字都在长度范围内,将每个数字放到对应的下标位置,判断当前数字是否与该位置的数字相等
*/
fun findRepeatNumber3(nums: IntArray): Int {
for (i in nums.indices) {
val n = nums[i]
if (i != n) {
if (nums[n] == n) {
return n
} else {
nums[i] = nums[n]
nums[n] = n
}
}
}
return -1
} | [
{
"class_path": "zys0909__CodeLabs__869c7c2/com/leecode/array/Code2Kt.class",
"javap": "Compiled from \"Code2.kt\"\npublic final class com.leecode.array.Code2Kt {\n public static final int findRepeatNumber1(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String nums\n ... |
zys0909__CodeLabs__869c7c2/src/com/leecode/array/Code3.kt | package com.leecode.array
/**
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof
*/
/**
* 申请一个新数组,T(n) ,O(n)
*/
fun exchange1(nums: IntArray): IntArray {
var start = 0
var end = nums.size - 1
val temp = IntArray(nums.size)
for (i in nums.indices) {
if (nums[i].and(1) == 1) {
temp[start++] = nums[i]
} else {
temp[end--] = nums[i]
}
}
return temp
}
/**
* 双指针法,T(n2),O(1)
* start 从前往后找第一个偶数,end从后往前找最后一个奇数,找到后交换位置
*/
fun exchange2(nums: IntArray): IntArray {
var start = 0
var end = nums.size - 1
var temp: Int
while (start < end) {
while (start < end && nums[start].and(1) == 1) {
start++
}
while (start < end && nums[end].and(1) == 0) {
end--
}
if (start < end) {
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
}
}
return nums
}
/**
* 快慢指针
*/
fun exchange3(nums: IntArray): IntArray {
var i = 0
var j = 0
var temp: Int
while (i < nums.size) {
if (nums[i].and(1) == 1) {
if (i != j) {
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
j++
}
i++
}
return nums
} | [
{
"class_path": "zys0909__CodeLabs__869c7c2/com/leecode/array/Code3Kt.class",
"javap": "Compiled from \"Code3.kt\"\npublic final class com.leecode.array.Code3Kt {\n public static final int[] exchange1(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String nums\n ... |
zys0909__CodeLabs__869c7c2/src/com/leecode/array/Code7.kt | package com.leecode.array
/**
给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后面的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
*/
fun main() {
val nums = intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4)
val i = removeDuplicates(nums)
System.arraycopy(nums, 0, nums, 0, i)
println(nums.joinToString())
}
fun removeDuplicates(nums: IntArray): Int {
var i = 0
var j = 1
while (j < nums.size) {
if (nums[i] != nums[j]) {
i++
nums[i] = nums[j]
}
j++
}
return i + 1
} | [
{
"class_path": "zys0909__CodeLabs__869c7c2/com/leecode/array/Code7Kt.class",
"javap": "Compiled from \"Code7.kt\"\npublic final class com.leecode.array.Code7Kt {\n public static final void main();\n Code:\n 0: bipush 10\n 2: newarray int\n 4: astore_1\n 5: aload_1\n... |
vishal-sehgal__kotlin-coding-interview__f83e929/ctci/arrays_and_strings/_02_check_permutation/CheckPermutation.kt | package ctci.arrays_and_strings._02_check_permutation
/**
* #1.2
*
* Check Permutation: Given two strings, write a method to decide if one is a permutation
* of the other.
*/
class CheckPermutation {
/**
* Determines whether two given strings are permutations of each other.
*
* Time Complexity: O(n), where n is the length of the input strings.
*
* @param string1 The first string to be checked for permutation.
* @param string2 The second string to be checked for permutation.
* @return `true` if the strings are permutations, `false` otherwise.
*/
fun arePermutationsSolutionOne(string1: String, string2: String): Boolean {
if ((string1.length != string2.length))
return false
val charCount = mutableMapOf<Char, Int>()
string1.forEach {
charCount[it] = charCount.getOrDefault(it, 0) + 1
}
return string2.all {
charCount[it]?.let { count ->
count > 0 && charCount.put(it, count - 1) != null
} ?: false
}
}
/**
* Time Complexity: O(n), where n is the length of the input strings.
*/
fun arePermutationsSolutionTwo(string1: String, string2: String): Boolean {
if (string1.length != string2.length) return false
return stringToCountMap(string1) == stringToCountMap(string2)
}
/**
* Converts a string into a character count map.
*
* This function takes a string as input and creates a mutable map where each character
* in the string is a key, and the corresponding value is the count of occurrences of that character.
* It iterates through the characters of the string, updating the count in the map accordingly.
*
* @param string The input string to be converted into a character count map.
* @return A mutable map with characters as keys and their counts as values.
*/
private fun stringToCountMap(string: String): MutableMap<Char, Int> {
val charCount = mutableMapOf<Char, Int>()
string.forEach {
charCount[it] = charCount.getOrDefault(it, 0) + 1
}
return charCount
}
}
fun main() {
val string1 = "abc"
val string2 = "cab"
val string3 = "bca"
println("Are $string1 & $string2 Permutations? ${CheckPermutation().arePermutationsSolutionOne(string1, string2)}")
println("Are $string1 & $string2 Permutations? ${CheckPermutation().arePermutationsSolutionTwo(string1, string2)}")
println("Are $string2 & $string3 Permutations? ${CheckPermutation().arePermutationsSolutionOne(string2, string3)}")
println("Are $string2 & $string3 Permutations? ${CheckPermutation().arePermutationsSolutionTwo(string2, string3)}")
} | [
{
"class_path": "vishal-sehgal__kotlin-coding-interview__f83e929/ctci/arrays_and_strings/_02_check_permutation/CheckPermutation.class",
"javap": "Compiled from \"CheckPermutation.kt\"\npublic final class ctci.arrays_and_strings._02_check_permutation.CheckPermutation {\n public ctci.arrays_and_strings._02_c... |
vishal-sehgal__kotlin-coding-interview__f83e929/ctci/arrays_and_strings/_01_is_unique/IsUnique.kt | package ctci.arrays_and_strings._01_is_unique
/**
* #1.1
*
* Is Unique: Implement an algorithm to determine if a string has all unique characters.
* What if you can not use additional data structures?
*/
fun main() {
val string1 = "vishal"
val string2 = "sehgal"
val string3 = "linkedin"
val string4 = "google"
println("String: $string1 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string1)}")
println("String: $string2 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string2)}")
println("String: $string3 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string3)}")
println("String: $string4 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string4)}")
println()
println("String: $string1 has all unique characters: ${IsUnique().hasUniqueCharactersBest(string1)}")
println("String: $string2 has all unique characters: ${IsUnique().hasUniqueCharactersBest(string2)}")
println("String: $string3 has all unique characters: ${IsUnique().hasUniqueCharactersBest(string3)}")
println("String: $string4 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string4)}")
}
class IsUnique {
/**
* Determines whether a given string has all unique characters.
*
* Time complexity: O(n), where n is the length of input string.
*
* Here's a breakdown of the time complexity:
*
* string.toSet(): This converts the string to a set, which involves iterating through each
* character in the string to build the set. In the worst case, this operation has a time complexity of O(n),
* where n is the length of the string.
*
* string.length == string.toSet().size: This checks if the length of the original string is equal
* to the size of the set. The size operation on a set is typically a constant-time operation.
*
* Therefore, the dominant factor in determining the time complexity is the conversion of the string
* to a set, resulting in a total time complexity of O(n), where n is the length of the input string.
* The function's runtime scales linearly with the size of the input.
*
*
* @param string The input string to be checked for unique characters.
* @return `true` if all characters in the string are unique, `false` otherwise.
*/
fun hasUniqueCharactersBest(string: String) = string.length == string.toSet().size
/**
* Determines whether a given string has all unique characters.
*
* Time complexity: O(n), where n is the number of characters in the string.
*
* @param string The input string to be checked for unique characters.
* @return `true` if all characters in the string are unique, `false` otherwise.
*/
fun hasUniqueCharactersBetter(string: String): Boolean {
//Assuming ASCII character set (8-bit)
//The string can not have all unique characters if it's length is greater than 128
if (string.length > 128) {
return false
}
val charSet = BooleanArray(128)
for (char in string) {
val index = char.code
if (charSet[index]) {
return false
}
charSet[index] = true
}
return true // All char are unique.
}
} | [
{
"class_path": "vishal-sehgal__kotlin-coding-interview__f83e929/ctci/arrays_and_strings/_01_is_unique/IsUnique.class",
"javap": "Compiled from \"IsUnique.kt\"\npublic final class ctci.arrays_and_strings._01_is_unique.IsUnique {\n public ctci.arrays_and_strings._01_is_unique.IsUnique();\n Code:\n ... |
mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/round1a/d.kt | package codechef.snackdown2021.round1a
import kotlin.math.abs
private fun solve(): Int {
readLn()
val a = readInts().sorted()
if (a.size == 2) return 0
var ans = minOf(makeEqual(a.drop(1)), makeEqual(a.dropLast(1))).coerceInInt()
var i = 1
var j = a.lastIndex - 1
val borders = a[0] + a.last()
while (i < j) {
ans = minOf(ans, abs(a[i] + a[j] - borders))
if (a[i] + a[j] < borders) i++ else j--
}
return ans
}
private fun makeEqual(a: List<Int>): Long {
val prefixSums = a.runningFold(0L, Long::plus)
fun sum(from: Int, to: Int) = prefixSums[to] - prefixSums[from]
return a.indices.minOf { a[it] * (2L * it - a.size) + sum(it, a.size) - sum(0, it) }
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { println(solve()) }
private fun Long.coerceInInt() = if (this >= Int.MAX_VALUE) Int.MAX_VALUE else if (this <= Int.MIN_VALUE) Int.MIN_VALUE else toInt()
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/round1a/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codechef.snackdown2021.round1a.DKt {\n private static final int solve();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/l... |
mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/qual/d_tl.kt | package codechef.snackdown2021.qual
private fun solve() {
val (n, m) = readInts()
val nei = List(n) { mutableListOf<Int>() }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val degree = IntArray(n) { nei[it].size }
val byDegree = List(n) { mutableSetOf<Int>() }
for (v in nei.indices) byDegree[degree[v]].add(v)
val mark = BooleanArray(n)
var minDegree = 0
var maxSeenMinDegree = 0
val ans = IntArray(n)
for (iter in nei.indices) {
while (byDegree[minDegree].isEmpty()) minDegree++
maxSeenMinDegree = maxOf(maxSeenMinDegree, minDegree)
val v = byDegree[minDegree].first()
ans[v] = n - iter
byDegree[minDegree].remove(v)
mark[v] = true
for (u in nei[v]) {
if (mark[u]) continue
byDegree[degree[u]].remove(u)
degree[u]--
byDegree[degree[u]].add(u)
minDegree = minOf(minDegree, degree[u])
}
}
println(maxSeenMinDegree)
println(ans.joinToString(" "))
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/qual/D_tlKt.class",
"javap": "Compiled from \"d_tl.kt\"\npublic final class codechef.snackdown2021.qual.D_tlKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInts:()L... |
mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/goodranking_randomized.kt | package codechef.snackdown2021.preelim
import java.util.*
private fun solve(magic: Int = 96): List<Int> {
val n = readInt()
val e = List(n) { readLn() }
val diff = (n + 1) / 2
fun won(i: Int, j: Int) = e[i][j] == '1'
val level = IntArray(n)
val r = Random(566)
var tries = 0
for (mid in e.indices.shuffled(r)) {
val (weak, strong) = (e.indices - mid).partition { won(mid, it) }.toList().map { it.toMutableList() }
if (maxOf(weak.size, strong.size) > diff + 1) continue
if (++tries == magic) break
level.fill(0)
for (a in listOf(weak, strong)) {
for (i in a.indices) for (j in 0 until i) {
if (won(a[i], a[j])) level[a[i]]++ else level[a[j]]++
}
a.sortBy { level[it] }
}
val p = weak + mid + strong
var good = true
for (i in p.indices) for (j in i + 1..minOf(i + diff, n - 1)) {
if (won(p[i], p[j])) {
good = false
break
}
}
if (good) {
return p.toIntArray().reversed().map { it + 1 }
}
}
return listOf(-1)
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { println(solve().joinToString(" ")) }
private fun readLn() = readLine()!!.trim()
private fun readInt() = readLn().toInt()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/Goodranking_randomizedKt$solve$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codechef.snackdown2021.preelim.Goodranking_randomizedKt$solve$$inlined$sortBy$1<T> implements java.ut... |
mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/slippers.kt | package codechef.snackdown2021.preelim
private const val MAX_S = 200_000
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) {
readLn()
val a = readInts()
val fenwickTree = FenwickTree(MAX_S + 1)
var ans = 1.toModular()
for (x in a) {
val added = 1 + fenwickTree.sum(x).toModular()
fenwickTree[x] = (fenwickTree[x].toInt() + added).x.toLong()
ans += added
}
println(ans)
}
private fun Int.toModular() = Modular(this)//toDouble()
private fun Long.toModular() = Modular(this)//toDouble()
private class Modular {
companion object {
const val M = 998244353
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
constructor(value: Long) { x = (value % M).toInt().let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
class FenwickTree(n: Int) {
var t: LongArray
fun add(i: Int, value: Long) {
var j = i
while (j < t.size) {
t[j] += value
j += j + 1 and -(j + 1)
}
}
fun sum(i: Int): Long {
var j = i
var res: Long = 0
j--
while (j >= 0) {
res += t[j]
j -= j + 1 and -(j + 1)
}
return res
}
fun sum(start: Int, end: Int): Long {
return sum(end) - sum(start)
}
operator fun get(i: Int): Long {
return sum(i, i + 1)
}
operator fun set(i: Int, value: Long) {
add(i, value - get(i))
}
init {
t = LongArray(n)
}
}
private fun readLn() = readLine()!!.trim()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/SlippersKt.class",
"javap": "Compiled from \"slippers.kt\"\npublic final class codechef.snackdown2021.preelim.SlippersKt {\n private static final int MAX_S;\n\n public static final void main(java.lang.String[]);\n Co... |
mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/guessrow.kt | package codechef.snackdown2021.preelim
import java.util.*
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) {
val (tests, n) = readInts()
val desired = n / 2
val all = 1..n
val cnk = List(n + 1) { LongArray(it + 1) { 1 } }
for (i in 2..n) for (j in 1 until i) cnk[i][j] = cnk[i - 1][j - 1] + cnk[i - 1][j]
fun cnk(i: Int, j: Int) = cnk[i].getOrElse(j) { 0 }
fun prob(asked: Int, ones: Int, density: Int) =
1.0 * cnk(asked, ones) * cnk(n - asked, density - ones) / cnk(n, density)
val prob = List(n + 1) { asked -> DoubleArray(asked + 1) { ones ->
prob(asked, ones, desired) / all.sumOf { prob(asked, ones, it) }
} }
val random = Random(566)
fun shuffle() = (0 until n).shuffled(random)
fun solve() {
val verShuffle = shuffle()
val horShuffle = List(n) { shuffle() }
fun ask(x: Int, y: Int): Int {
println("? ${verShuffle[x] + 1} ${horShuffle[x][y] + 1}")
return readInt()
}
fun answer(x: Int) {
println("! ${verShuffle[x] + 1}")
}
val asked = IntArray(n)
val ones = IntArray(n)
val treeSet = TreeSet<Int>(compareBy({ prob[asked[it]][ones[it]] }, { it }))
treeSet.addAll(asked.indices)
while (true) {
val x = treeSet.pollLast()!!
ones[x] += ask(x, asked[x]++)
if (asked[x] == n && ones[x] == desired) return answer(x)
treeSet.add(x)
}
}
repeat(tests) { solve() }
}
private fun readLn() = readLine()!!.trim()
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/GuessrowKt.class",
"javap": "Compiled from \"guessrow.kt\"\npublic final class codechef.snackdown2021.preelim.GuessrowKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc... |
mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/decsubk.kt | package codechef.snackdown2021.preelim
private fun solve(): IntArray {
val (_, k) = readInts()
val a = readInts().sorted()
val b = IntArray(a.size)
val used = BooleanArray(a.size)
for (x in a.indices) {
fun isGood(i: Int): Boolean {
b[x] = a[i]
var y = x + 1
for (j in a.indices) if (!used[j] && j != i) b[y++] = a[j]
val max = longestNondecreasingSubsequence(b)
b.reverse(x + 1, b.size)
val min = longestNondecreasingSubsequence(b)
return k in min..max
}
val i = a.indices.firstOrNull { !used[it] && isGood(it) } ?: return intArrayOf(-1)
used[i] = true
}
return b
}
private fun longestNondecreasingSubsequence(a: IntArray): Int {
val dp = IntArray(a.size)
for (i in a.indices) {
for (j in 0 until i) if (a[j] <= a[i]) dp[i] = maxOf(dp[i], dp[j])
dp[i]++
}
return dp.maxOrNull()!!
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { println(solve().joinToString(" ")) }
private fun readLn() = readLine()!!.trim()
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codechef/snackdown2021/preelim/DecsubkKt.class",
"javap": "Compiled from \"decsubk.kt\"\npublic final class codechef.snackdown2021.preelim.DecsubkKt {\n private static final int[] solve();\n Code:\n 0: invokestatic #10 // Met... |
mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day4/k.kt | package workshops.moscow_prefinals2020.day4
fun main() {
val (n, m) = readInts()
val g = MutableList(n) { DoubleArray(n) }
repeat(m) {
val (uIn, vIn, resistance) = readInts()
for ((u, v) in listOf(uIn, vIn).map { it - 1 }.withReversed()) {
g[u][v] += 1.0 / resistance
g[u][u] -= 1.0 / resistance
}
}
val potential = List(n) { kirchhoff(g, 0, it) }
val current = List(n) { v -> g.indices.sumByDouble { potential[v][it] * g[0][it] } }
val ans = List(n) { v -> DoubleArray(v) { u ->
if (u == 0) return@DoubleArray 1 / current[v]
fun newPotential(w: Int) = potential[u][w] - potential[v][w] * current[u] / current[v]
val (npu, npv) = listOf(u, v).map(::newPotential)
1 / g.indices.sumByDouble { g[u][it] * (newPotential(it) - npu) / (npv - npu) }
}}
println(List(readInt()) {
val (u, v) = readInts().map { it - 1 }.sorted()
ans[v][u]
}.joinToString("\n"))
}
private fun kirchhoff(g: List<DoubleArray>, @Suppress("SameParameterValue") u: Int, v: Int): DoubleArray {
val gClone = g.map { it.clone() }
listOf(u, v).forEach { gClone[it].fill(0.0); gClone[it][it] = 1.0 }
val h = DoubleArray(gClone.size).also { it[v] = 1.0 }
return gauss(gClone, h)
}
private fun gauss(a: List<DoubleArray>, b: DoubleArray): DoubleArray {
val m = a.size
val n = a[0].size
val pos = IntArray(m)
for (i in 0 until m) {
val ai = a[i]
val s = (0 until n).maxByOrNull { ai[it].abs() }!!
pos[i] = s
for (k in 0 until m) if (k != i) {
val ak = a[k]
val c = -ak[s] / ai[s]
for (j in 0 until n) ak[j] += c * ai[j]
b[k] += c * b[i]
}
}
val ans = DoubleArray(n)
for (i in 0 until m) ans[pos[i]] = b[i] / a[i][pos[i]]
return ans
}
private fun <T> Iterable<T>.withReversed() = listOf(toList(), reversed())
private fun Double.abs() = kotlin.math.abs(this)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day4/KKt.class",
"javap": "Compiled from \"k.kt\"\npublic final class workshops.moscow_prefinals2020.day4.KKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt... |
mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day4/c.kt | package workshops.moscow_prefinals2020.day4
fun main() {
val s = readLine()!!
val initMask = s.reversed().replace("(", "0").replace(")", "1").toLong(2)
val memo = List(s.length + 1) { mutableMapOf<Long, Double>() }
memo[0][0] = 1.0
fun solve(n: Int, mask: Long): Double {
memo[n][mask]?.also { return it }
if ((mask and 1) != 0L || (mask shr (n - 1)) == 0L) return 0.0
var options = 0
var sum = 0.0
for (j in 0 until n) if (((mask shr j) and 1L) != 0L) {
for (i in 0 until j) if (((mask shr i) and 1L) == 0L) {
sum += solve(n - 2, (if (j + 1 < n) (mask shr (j + 1) shl (j - 1)) else 0) +
(if (i + 1 < j) ((mask and ((1L shl j) - 1)) shr (i + 1) shl i) else 0) +
(if (0 < i) (mask and ((1L shl i) - 1)) else 0))
options++
}
}
val res = if (options == 0) 0.0 else sum / options
memo[n][mask] = res
return res
}
println(solve(s.length, initMask))
}
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day4/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class workshops.moscow_prefinals2020.day4.CKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kotlin/... |
mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day3/k.kt | package workshops.moscow_prefinals2020.day3
fun main() {
val (x, y, z) = List(3) { readInts().drop(1).reversed() }
var (low, high) = maxOf((x + y + z).maxOrNull()!!, 1).toLong() to Long.MAX_VALUE / 2
binarySearch@while (low + 1 < high) {
val b = (low + high) / 2
val zNew = LongArray(z.size)
var tooLarge = false
fun add(index: Int, value: Long) {
if (index >= zNew.size) tooLarge = true else zNew[index] += value
}
for (i in x.indices) for (j in y.indices) {
add(i + j, x[i].toLong() * y[j])
for (k in i + j until zNew.size) {
if (zNew[k] < b) break
add(k + 1, zNew[k] / b)
zNew[k] %= b
}
if (tooLarge) {
low = b
continue@binarySearch
}
}
for (k in zNew.indices.reversed()) {
if (zNew[k] == z[k].toLong()) continue
if (zNew[k] > z[k]) low = b else high = b
continue@binarySearch
}
return println(b)
}
println("impossible")
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day3/KKt.class",
"javap": "Compiled from \"k.kt\"\npublic final class workshops.moscow_prefinals2020.day3.KKt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: istore_1\n 2: new ... |
mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day3/l.kt | package workshops.moscow_prefinals2020.day3
private fun solve() {
val a = mutableMapOf<Int, MutableMap<Int, Int>>()
var ans = 0
repeat(readInt()) {
val (s, vIn) = readStrings()
val v = vIn.toInt()
if (v <= 0) return@repeat
val hashing = Hashing(s)
var maxSeen = 0
for (len in a.keys) if (len < s.length) {
val map = a[len]!!
for (i in 0..s.length - len) {
val hash = hashing.hash(i, i + len)
val score = map[hash] ?: continue
maxSeen = maxOf(maxSeen, score)
}
}
val map = a.computeIfAbsent(s.length) { mutableMapOf() }
val hash = hashing.hash(0, s.length)
val score = map.compute(hash) { _, oldValue -> v + maxOf(maxSeen, oldValue ?: 0) }!!
ans = maxOf(ans, score)
}
println(ans)
}
private const val M = 1_000_000_007
private class Hashing(s: String, x: Int = 566239) {
val h = IntArray(s.length + 1)
val t = IntArray(s.length + 1)
fun hash(from: Int, to: Int): Int {
var res = ((h[to] - h[from] * t[to - from].toLong()) % M).toInt()
if (res < 0) res += M
return res
}
init {
t[0] = 1
for (i in s.indices) {
t[i + 1] = (t[i] * x.toLong() % M).toInt()
h[i + 1] = ((h[i] * x.toLong() + s[i].toLong()) % M).toInt()
}
}
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day3/LKt.class",
"javap": "Compiled from \"l.kt\"\npublic final class workshops.moscow_prefinals2020.day3.LKt {\n private static final int M;\n\n private static final void solve();\n Code:\n 0: new #8... |
mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day3/e.kt | package workshops.moscow_prefinals2020.day3
private typealias State = Int
private fun solve() {
val (hei, wid) = readInts()
val field = List(hei) { readLn().toCharArray() }
val state = IntArray(hei) { -1 }
fun arrayToInt(): Int {
var m = 0
for (i in 0 until hei) {
val bits = state[i] and 15
m = m or (bits shl (4 * i))
}
return m
}
fun intToArray(m: Int) {
for (i in 0 until hei) {
val bits = (m shr (4 * i)) and 15
state[i] = if (bits == 15) -1 else bits
}
}
while (true) {
var improved = false
for (y1 in 0 until hei) for (y2 in listOf(y1 - 1, y1 + 1)) if (y2 in 0 until hei) {
for (x1 in 0 until wid) for (x2 in listOf(x1 - 1, x1 + 1)) if (x2 in 0 until wid) {
for (spread in listOf("ce", "ec")) {
if ("" + field[y1][x1] + field[y1][x2] + field[y2][x1] == spread + spread[1]) {
if (field[y2][x2] == spread[0]) return println(-1)
if (field[y2][x2] == '.') improved = true
field[y2][x2] = spread[1]
}
}
}
}
if (!improved) break
}
val init: State = arrayToInt()
var a = mapOf(init to 0)
val inf = hei * wid * 5
var ans = inf
val future = List(hei) { BooleanArray(wid) }
var moreC = false
for (x in wid - 1 downTo 0) for (y in hei - 1 downTo 0) {
future[y][x] = moreC
moreC = moreC || field[y][x] == 'c'
}
for (x in 0 until wid) for (y in 0 until hei) {
val b = mutableMapOf<State, Int>()
val mayTake = (0..1).filter { field[y][x] != "ce"[it] }
for ((stateInt, perimeter) in a) for (take in mayTake) {
intToArray(stateInt)
val left = state[y]
val up = state.getOrElse(y - 1) { -1 }
val leftWall = if (left >= 0) 1 else 0
val upWall = if (up >= 0) 1 else 0
val newPerimeter = perimeter + if (take == 0) 0 else 4 - 2 * leftWall - 2 * upWall
var bad = false
if (take == 0) {
state[y] = -1
bad = (left >= 0) && !state.contains(left)
if (bad) {
if (state.maxOrNull() == -1 && !future[y][x]) ans = minOf(ans, newPerimeter)
}
} else {
when (listOf(left, up).count { it == -1 }) {
2 -> state[y] = hei
1 -> {
state[y] = maxOf(left, up)
if (left == -1 && y + 1 < hei && state[y + 1] == up) bad = true
}
0 -> {
state[y] = up
state.indices.forEach { if (state[it] == left) state[it] = up }
}
}
}
if (bad) continue
val repaint = mutableMapOf<Int, Int>()
for (i in state.indices) {
val c = state[i]
if (c == -1) continue
if (c !in repaint.keys) repaint[c] = repaint.size
state[i] = repaint[c]!!
}
val newStateInt = arrayToInt()
b[newStateInt] = minOf(b.getOrDefault(newStateInt, inf), newPerimeter)
}
a = b
}
ans = minOf(ans, a.filter { intToArray(it.key); state.maxOrNull()!! <= 0 }.values.minOrNull() ?: inf)
println(if (ans < inf) ans else -1)
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/workshops/moscow_prefinals2020/day3/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class workshops.moscow_prefinals2020.day3.EKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readI... |
mikhail-dvorkin__competitions__3095312/codeforces/round584/e1.kt | package codeforces.round584
private fun solve() {
val (n, m) = readInts()
val a = List(n) { readInts() }
val b = List(m) { i -> a.map { it[i] } }.sortedByDescending { it.maxOrNull() }.take(n)
println(solve(b, 1, b[0]))
}
private fun solve(b: List<List<Int>>, x: Int, best: List<Int>): Int {
val bestInit = best.sum()
if (x == b.size) return bestInit
return best.indices.mapNotNull { i ->
val newBest = List(best.size) { maxOf(best[it], b[x][(it + i) % best.size]) }
if (newBest.sum() > bestInit) solve(b, x + 1, newBest) else null
}.maxOrNull() ?: solve(b, x + 1, best)
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round584/E1Kt.class",
"javap": "Compiled from \"e1.kt\"\npublic final class codeforces.round584.E1Kt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/round584/f.kt | package codeforces.round584
private const val M = 1_000_000_007
fun main() {
val (n, m) = readInts()
val nei = List(n) { mutableListOf<Pair<String, Int>>() }
repeat(m) { i ->
val label = (i + 1).toString()
val (a, b) = readInts().map { it - 1 }
nei[a].add(label to b)
nei[b].add(label to a)
}
val gap = m.toString().length
val inf = gap * n
val dist = MutableList(n) { inf }
val text = MutableList(n) { "" }
val rem = MutableList(n) { 0 }
val byDist = List(inf) { mutableSetOf<Int>() }
dist[0] = 0
byDist[0].add(0)
for (curDist in byDist.indices) {
for (v in byDist[curDist]) {
if (dist[v] < curDist) continue
for ((label, u) in nei[v]) {
val newDist = curDist + label.length
val newText = text[v] + label
if (newDist >= dist[u] && !(newDist == dist[u] && newText < text[u])) continue
dist[u] = newDist
text[u] = newText
rem[u] = ((rem[v].toString() + label).toLong() % M).toInt()
byDist[newDist].add(u)
}
}
if (curDist % gap != 0) continue
val prefixes = mutableListOf<String>()
for (mode in 0..1) {
val map = prefixes.sorted().withIndex().associate { it.value to it.index.toString().padStart(gap, '0') }
for (c in curDist + 1..minOf(curDist + gap, inf - 1)) {
for (v in byDist[c]) {
if (dist[v] < c) continue
val take = text[v].length - (c - curDist)
val prefix = text[v].take(take)
prefixes.add(prefix)
if (mode == 1) text[v] = map[prefix] + text[v].drop(take)
}
}
}
}
rem.drop(1).forEach { println(it) }
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round584/FKt.class",
"javap": "Compiled from \"f.kt\"\npublic final class codeforces.round584.FKt {\n private static final int M;\n\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readIn... |
mikhail-dvorkin__competitions__3095312/codeforces/round773/b.kt | package codeforces.round773
private fun solve() {
readInt()
val a = readInts().toIntArray()
val groups = a.groupBy { it }
if (groups.values.any { it.size % 2 != 0 }) return println(-1)
var start = 0
val insertions = mutableListOf<Pair<Int, Int>>()
val tandems = mutableListOf<Int>()
var x = 0
while (start < a.size) {
val repeat = a.drop(start + 1).indexOf(a[start]) + start + 1
val rev = mutableListOf<Int>()
for (i in start + 1 until repeat) {
insertions.add(x + (repeat - start) + (i - start) to a[i])
rev.add(a[i])
}
tandems.add((repeat - start) * 2)
x += (repeat - start) * 2
rev.reverse()
for (i in rev.indices) {
a[start + 2 + i] = rev[i]
}
start += 2
}
println(insertions.size)
for (insertion in insertions) {
println("${insertion.first} ${insertion.second}")
}
println(tandems.size)
println(tandems.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round773/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round773.BKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: pop\n 4:... |
mikhail-dvorkin__competitions__3095312/codeforces/round576/e.kt | package codeforces.round576
fun main() {
val (n, rectNum) = readInts()
val rectangles = Array(rectNum) { readInts() }
val xSet = mutableSetOf(0, n)
val ySet = mutableSetOf(0, n)
for ((x1, y1, x2, y2) in rectangles) {
xSet.add(x1 - 1)
xSet.add(x2)
ySet.add(y1 - 1)
ySet.add(y2)
}
val xs = xSet.sorted()
val ys = ySet.sorted()
val m = xs.size + ys.size + 2
val c = Array(m) { IntArray(m) }
for (i in 0 until xs.size - 1) {
c[m - 2][i] = xs[i + 1] - xs[i]
}
for (j in 0 until ys.size - 1) {
c[xs.size + j][m - 1] = ys[j + 1] - ys[j]
}
for ((x1, y1, x2, y2) in rectangles) {
for (i in xs.indices) {
if ((xs[i] < x1 - 1) || (xs[i] >= x2)) continue
for (j in ys.indices) {
if ((ys[j] < y1 - 1) || (ys[j] >= y2)) continue
c[i][xs.size + j] = minOf(xs[i + 1] - xs[i], ys[j + 1] - ys[j])
}
}
}
println(edmonsKarp(c, m - 2, m - 1))
}
fun edmonsKarp(c: Array<IntArray>, s: Int, t: Int): Int {
val n = c.size
val f = Array(n) { IntArray(n) }
val queue = IntArray(n)
val prev = IntArray(n)
var res = 0
while (true) {
queue[0] = s
var low = 0
var high = 1
prev.fill(-1)
prev[s] = s
while (low < high && prev[t] == -1) {
val v = queue[low]
low++
for (u in 0 until n) {
if (prev[u] != -1 || f[v][u] == c[v][u]) {
continue
}
prev[u] = v
queue[high] = u
high++
}
}
if (prev[t] == -1) {
break
}
var flow = Integer.MAX_VALUE / 2
var u = t
while (u != s) {
flow = minOf(flow, c[prev[u]][u] - f[prev[u]][u])
u = prev[u]
}
u = t
while (u != s) {
f[prev[u]][u] += flow
f[u][prev[u]] -= flow
u = prev[u]
}
res += flow
}
return res
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round576/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.round576.EKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/round576/d.kt | package codeforces.round576
fun main() {
val n = readInt()
val f = Array(n) { readLn().map { if (it == '#') 1 else 0 } }
val cum = Array(n + 1) { IntArray(n + 1) }
for (i in 0 until n) {
for (j in 0 until n) {
cum[i + 1][j + 1] = cum[i][j + 1] + cum[i + 1][j] - cum[i][j] + f[i][j]
}
}
val dp = Array(n + 1) { Array(n + 1) { Array(n + 1) { IntArray(n + 1) }}}
for (i1 in n - 1 downTo 0) {
for (i2 in i1 + 1..n) {
for (j1 in n - 1 downTo 0) {
for (j2 in j1 + 1..n) {
if (sum(cum, i1, j1, i2, j2) == 0) continue
var res = maxOf(i2 - i1, j2 - j1)
for (i in i1 until i2) {
if (sum(cum, i, j1, i + 1, j2) != 0) continue
res = minOf(res, dp[i1][j1][i][j2] + dp[i + 1][j1][i2][j2])
}
for (j in j1 until j2) {
if (sum(cum, i1, j, i2, j + 1) != 0) continue
res = minOf(res, dp[i1][j1][i2][j] + dp[i1][j + 1][i2][j2])
}
dp[i1][j1][i2][j2] = res
}
}
}
}
println(dp[0][0][n][n])
}
private fun sum(cum: Array<IntArray>, i1: Int, j1: Int, i2: Int, j2: Int) =
cum[i2][j2] - cum[i1][j2] - cum[i2][j1] + cum[i1][j1]
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round576/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.round576.DKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/round631/c.kt | package codeforces.round631
private fun solve(): String {
val (h, g) = readInts()
val a = (listOf(0) + readInts()).toIntArray()
val bottomLevel = 1 shl (h - 1)
tailrec fun siftDown(i: Int, act: Boolean): Int {
val j = if (i >= bottomLevel) 0 else if (a[2 * i] >= a[2 * i + 1]) 2 * i else 2 * i + 1
if (act) a[i] = a[j]
return if (a[j] == 0) i else siftDown(j, act)
}
val toLeave = 1 shl g
val ans = mutableListOf<Int>()
for (i in 1 until toLeave) {
while (siftDown(i, false) >= toLeave) {
ans.add(i)
siftDown(i, true)
}
}
return "${a.fold(0L, Long::plus)}\n${ans.joinToString(" ")}"
}
fun main() = println(List(readInt()) { solve() }.joinToString("\n"))
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round631/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round631.CKt {\n private static final java.lang.String solve();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/Lis... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes1/f.kt | package codeforces.kotlinheroes1
fun main() {
val (n, m, canIncrease) = readInts()
val a = readInts().sorted()
val acc = mutableListOf(0L)
for (i in 0 until n) { acc.add(acc[i] + a[i]) }
var ans = a.fold(0L, Long::plus)
for (left in 0..n - m) {
var low = a[left]
var high = a[left + (m - 1) / 2] + 1
while (low + 1 < high) {
val mid = (low + high) / 2
val index = a.binarySearch(mid, left, m)
val increases = (index - left) * 1L * mid - (acc[index] - acc[left])
if (increases <= canIncrease) {
low = mid
} else {
high = mid
}
}
val index = a.binarySearch(low, left, m)
val ops = (index - left) * 1L * low - (acc[index] - acc[left]) +
(acc[left + m] - acc[index]) - (left + m - index) * 1L * low
ans = minOf(ans, ops)
}
println(ans)
}
private fun List<Int>.binarySearch(value: Int, from: Int, length: Int): Int {
val binarySearch = this.binarySearch(value, from, from + length)
return if (binarySearch >= 0) binarySearch else -1 - binarySearch
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes1/FKt.class",
"javap": "Compiled from \"f.kt\"\npublic final class codeforces.kotlinheroes1.FKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes6/c.kt | package codeforces.kotlinheroes6
import kotlin.math.abs
private fun solve() {
val (n, xIn, yIn) = readInts()
val (x, y) = listOf(xIn, yIn).sorted().map { it - 1 }
val ans = List(n) { m ->
maxOf(solve(0, m, x), solve(m, n, y))
}.minOrNull()
println(ans)
}
private fun solve(from: Int, to: Int, x: Int): Int {
if (from == to) return 0
return minOf(dist(x, from), dist(x, to - 1)) + to - from - 1
}
private fun dist(x: Int, y: Int): Int {
return abs(x - y)
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes6/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.kotlinheroes6.CKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes6/g_wrong.kt | package codeforces.kotlinheroes6
import java.util.*
import kotlin.system.exitProcess
fun main() {
for (n in 1..20) solve(n)
solve(readInt())
}
private fun solve(n: Int) {
val set = List(2 * n + 1) { TreeSet<Int>() }
val score = IntArray(n + 1) { 0 }
val divs = List(n + 1) { mutableListOf<Int>() }
for (i in 1..n) set[0].add(i)
fun change(x: Int, delta: Int) {
set[n + score[x]].remove(x)
score[x] += delta
set[n + score[x]].add(x)
}
fun remove(x: Int) {
set[n + score[x]].remove(x)
score[x] = -1
}
for (i in 1..n) {
for (j in 2 * i..n step i) {
change(j, +1)
divs[j].add(i)
}
}
val ans = mutableListOf(0)
var bestScore = set.lastIndex
for (k in 1..n) {
while (set[bestScore].isEmpty()) bestScore--
var bonus = bestScore - n
val x = set[bestScore].last()
remove(x)
for (j in 2 * x..n step x) {
if (score[j] == -1) {
bonus--
continue
}
}
ans.add(ans.last() + bonus)
}
val fullSearch = researchFullSearch(n)
if (!fullSearch.contentEquals(ans.toIntArray())) {
println("! $n")
println(ans.drop(1).joinToString(" "))
println(fullSearch.drop(1).joinToString(" "))
println(researchStupid(n).drop(1).joinToString(" "))
exitProcess(0)
}
println(ans.drop(1).joinToString(" "))
}
private fun researchFullSearch(n: Int): IntArray {
val ans = IntArray(n + 1) { 0 }
for (mask in 0 until (1 shl n)) {
var count = 0
for (i in 0 until n) if (mask.hasBit(i)) for (j in 0 until n) if (!mask.hasBit(j) && (i + 1) % (j + 1) == 0) {
count++
}
if (count >= 17) {
println(count)
println(n)
println(mask.toString(2))
}
val size = mask.countOneBits()
ans[size] = maxOf(ans[size], count)
}
return ans
}
private fun researchStupid(n: Int): IntArray {
val ans = IntArray(n + 1) {
val k = n - it
var s = 0
for (i in k + 1..n) for (j in 1..k) {
if (i % j == 0) s++
}
s
}
return ans
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun Int.bit(index: Int) = shr(index) and 1
private fun Int.hasBit(index: Int) = bit(index) != 0
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes6/G_wrongKt.class",
"javap": "Compiled from \"g_wrong.kt\"\npublic final class codeforces.kotlinheroes6.G_wrongKt {\n public static final void main();\n Code:\n 0: iconst_1\n 1: istore_0\n 2: iload_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes6/e.kt | package codeforces.kotlinheroes6
private fun solve() {
readLn()
val a = readInts()
val st = SegmentsTreeMax(a.size)
val seen = IntArray(a.size + 1) { -1 }
for (i in a.indices) {
val x = a[i]
val prev = seen[x]
if (prev == -1) {
seen[x] = i
continue
}
val best = maxOf(st.get(prev, i), if (prev + 1 == i) 0 else 1)
st.set(prev, best + 2)
}
println(maxOf(st.get(0, a.size), 1))
}
fun main() = repeat(readInt()) { solve() }
private class SegmentsTreeMax(size: Int) {
val two: Int
val a: Array<Int>
init {
var t = 1
while (t < size) {
t *= 2
}
two = t
a = Array<Int>(2 * two, {_ -> 0})
}
fun get(from: Int, to: Int): Int {
var res = Integer.MIN_VALUE
var x = two + from
var y = two + to
while (x < y) {
if (x % 2 == 1) {
res = Math.max(res, a[x])
x++
}
if (y % 2 == 1) {
y--
res = Math.max(res, a[y])
}
x /= 2
y /= 2
}
return res
}
fun set(pos: Int, v: Int) {
var x = two + pos
a[x] = v
while (x >= 2) {
x /= 2
a[x] = Math.max(a[2 * x], a[2 * x + 1])
}
}
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes6/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.kotlinheroes6.EKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/String;... |
mikhail-dvorkin__competitions__3095312/codeforces/round606/c.kt | package codeforces.round606
import kotlin.math.sqrt
fun main() {
readLn()
val a = readInts()
val groups = a.groupBy { it }.toList().sortedByDescending { it.second.size }
val b = groups.map { it.second.size }
var bSelf = b.size
var bSum = 0
val (h, w) = (1..sqrt(a.size.toDouble()).toInt()).map { h ->
while (bSelf > 0 && b[bSelf - 1] <= h) bSum += b[--bSelf]
h to ((bSelf + bSum / h).takeIf { it >= h } ?: 0)
}.maxByOrNull { it.first * it.second }!!
println("${h * w}\n$h $w")
val f = List(h) { IntArray(w) }
var x = 0
for (group in groups) repeat(minOf(group.second.size, h)) {
f[x % h][(x % h + x / h) % w] = group.first
if (++x == h * w) return f.forEach { println(it.joinToString(" ")) }
}
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round606/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round606.CKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/String;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/round637/b.kt | package codeforces.round637
private val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010",
"1101011", "1101111", "1010010", "1111111", "1111011").map { it.toInt(2) }
fun main() {
val (n, k) = readInts()
val a = List(n) {
val shown = readLn().toInt(2)
digits.mapIndexedNotNull { d, digit ->
(d to Integer.bitCount(digit xor shown)).takeIf { digit.inv() and shown == 0 }
}
}
val can = List(n + 1) { BooleanArray(k + 1) }
can[n][0] = true
for (i in a.indices.reversed()) {
for ((_, need) in a[i]) {
for (j in 0..k - need) if (can[i + 1][j]) can[i][j + need] = true
}
}
var x = k
println(if (!can[0][x]) -1 else a.indices.joinToString("") { i ->
val (d, need) = a[i].last { can[i + 1].getOrFalse(x - it.second) }
x -= need
d.toString()
})
}
private fun BooleanArray.getOrFalse(index: Int) = getOrNull(index) ?: false
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round637/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round637.BKt {\n private static final java.util.List<java.lang.Integer> digits;\n\n public static final void main();\n Code:\n 0: invokestatic #... |
mikhail-dvorkin__competitions__3095312/codeforces/round637/c.kt | package codeforces.round637
fun main() {
readLn()
val d = readInts().sorted()
val (g, r) = readInts()
val inf = Int.MAX_VALUE
val mark = Array(g) { BooleanArray(d.size) { false } }
val queue = Array(g) { IntArray(d.size) }
val queueLow = IntArray(g)
val queueHigh = IntArray(g)
mark[0][0] = true
queueHigh[0] = 1
var ans = inf
var time = 0
while (time < ans) {
val mod = time % (g + r)
repeat(queueHigh[mod] - queueLow[mod]) {
val i = queue[mod][queueLow[mod]++]
if (mod + d.last() - d[i] <= g) ans = minOf(ans, time + d.last() - d[i])
for (i2 in intArrayOf(i - 1, i + 1)) {
val mod2 = (((d.getOrNull(i2) ?: continue) - d[i]).abs() + mod)
.let { if (it == g) 0 else it }
if (mod2 > g || mark[mod2][i2]) continue
mark[mod2][i2] = true
queue[mod2][queueHigh[mod2]++] = i2
}
}
if (++time % (g + r) == g) {
time += r
if (queueLow[0] == queueHigh[0]) break
}
}
println(if (ans < inf) ans else -1)
}
private fun Int.abs() = kotlin.math.abs(this)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round637/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round637.CKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/String;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/i.kt | package codeforces.kotlinheroes8
import java.util.*
private fun solve() {
val n = readInt()
val (from, toIn) = List(2) { readInts() }
data class Doctor(val id: Int, val from: Int, val to: Int)
val doctors = List(n) { Doctor(it, from[it], toIn[it] + 1) }
val low = doctors.sortedBy { it.from }.withIndex().maxOf { it.value.from - it.index }
val high = doctors.sortedBy { it.to }.withIndex().minOf { it.value.to - it.index }
if (low >= high) return println(-1)
val byStart = doctors.groupBy { it.from }
val queue = PriorityQueue<Doctor>(compareBy({ it.to }, { it.id }))
queue.addAll(doctors.filter { it.from <= low })
val ans = (low until low + n).map { time ->
val doctor = queue.poll()
if (doctor.to <= time) return println(-1)
queue.addAll(byStart[time + 1] ?: emptyList())
doctor.id
}
println(low)
println(ans.map { it + 1 }.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/IKt$solve$Doctor.class",
"javap": "Compiled from \"i.kt\"\npublic final class codeforces.kotlinheroes8.IKt$solve$Doctor {\n private final int id;\n\n private final int from;\n\n private final int to;\n\n public codeforces.k... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/h.kt | package codeforces.kotlinheroes8
fun main() {
val den = 1_000_000.toModular()
val (n, wid, hei) = readInts()
val (pSlash, pBackslash) = List(2) { Array(wid + hei + 1) { 1.toModular() } } // prob of being free
val (vertical, horizontal) = listOf(wid, hei).map { s -> BooleanArray(s + 1).also { it[0] = true; it[s] = true } }
repeat(n) {
val (x, y, pIn) = readInts()
val p = 1 - pIn / den
vertical[x] = true; horizontal[y] = true
pBackslash[x + y] *= p; pSlash[x - y + hei] *= p
}
val vertices = (wid + 1) * (hei + 1) + wid * hei
val edgesInitial = vertical.count { it } * hei + horizontal.count { it } * wid
var ans = (1 - vertices + edgesInitial).toModular()
for (x in 0..wid) for (y in 0..hei) {
if (!vertical[x] && !horizontal[y]) ans += pBackslash[x + y] * pSlash[x - y + hei]
if (x < wid && y < hei) ans += pBackslash[x + y + 1] * pSlash[x - y + hei]
if (x + 1 <= wid && y - 1 >= 0) ans += 2 * (1 - pBackslash[x + y])
if (x + 1 <= wid && y + 1 <= hei) ans += 2 * (1 - pSlash[x - y + hei])
}
println(ans)
}
private fun Int.toModular() = Modular(this)//toDouble()
private class Modular {
companion object {
const val M = 998244353
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/HKt.class",
"javap": "Compiled from \"h.kt\"\npublic final class codeforces.kotlinheroes8.HKt {\n public static final void main();\n Code:\n 0: ldc #7 // int 1000000\n 2: invokestatic ... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/e.kt | package codeforces.kotlinheroes8
private fun solve(): Int {
val n = readInt()
val s = readLn().map { "()".indexOf(it) }
val a = readLn()
val must = IntArray(n) { -1 }
val diff = BooleanArray(n)
for (i in a.indices) {
if (a[i] == '0') continue
if (must[i] == 1) return -1
must[i] = 0
must[i + 3] = 1
diff[i + 2] = true
}
val inf = n + 1
val ans = s.indices.fold(listOf(0, 0)) { prev, i -> List(2) { j ->
if (must[i] == 1 - j) inf else
(s[i] xor j) + if (diff[i]) prev[1 - j] else prev.minOrNull()!!
}}.minOrNull()!!
return if (ans >= inf) -1 else ans
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.kotlinheroes8.EKt {\n private static final int solve();\n Code:\n 0: invokestatic #9 // Method readInt:()I\n 3: istor... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/g.kt | package codeforces.kotlinheroes8
fun main() {
val (n, m) = readInts()
data class Attack(val warrior: Int, val barricade: Int, val damage: Int)
val attacks = List(n) { warrior ->
val (_, damages, barricadesLeft) = List(3) { readInts() }
List(damages.size) { Attack(warrior, m - barricadesLeft[it], damages[it]) }
}.flatten()
val st = SegmentsTreeSimple(n)
for (a in attacks.sortedBy { it.barricade }) {
val level = a.warrior - a.barricade
if (level < 0) continue
st[level] = maxOf(st[level], a.damage + maxOf(st.getMax(0, level), 0))
}
println(st.getMax(0, n))
}
class SegmentsTreeSimple(var n: Int) {
var max: LongArray
var size = 1
operator fun set(index: Int, value: Long) {
var i = size + index
max[i] = value
while (i > 1) {
i /= 2
max[i] = maxOf(max[2 * i], max[2 * i + 1])
}
}
operator fun get(index: Int): Long {
return max[size + index]
}
fun getMax(from: Int, to: Int): Long {
var fromVar = from
var toVar = to
fromVar += size
toVar += size
var res = Long.MIN_VALUE
while (fromVar < toVar) {
if (fromVar % 2 == 1) {
res = maxOf(res, max[fromVar])
fromVar++
}
if (toVar % 2 == 1) {
toVar--
res = maxOf(res, max[toVar])
}
fromVar /= 2
toVar /= 2
}
return res
}
init {
while (size <= n) {
size *= 2
}
max = LongArray(2 * size)
}
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/GKt$main$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.kotlinheroes8.GKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public codeforces.kotlinheroes8.G... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/f.kt | package codeforces.kotlinheroes8
fun main() {
val (n, m) = readInts()
val groups = List(2) { mutableListOf<IndexedValue<Int>>() }
repeat(n) {
val (k, t) = readInts()
groups[t - 1].add(IndexedValue(it, k))
}
val groupSum = groups.map { group -> group.sumOf { it.value } }
val can = BooleanArray(m + 1)
val how = Array<IndexedValue<Int>?>(m + 1) { null }
can[0] = true
for (series in groups[1]) for (i in m - series.value downTo 0) {
if (!can[i] || can[i + series.value]) continue
can[i + series.value] = true
how[i + series.value] = series
}
val x = can.indices.firstOrNull { can[it] && maxOf(2 * it - 1, 2 * (groupSum[1] - it)) + groupSum[0] <= m }
?: return println(-1)
val odd = mutableListOf<IndexedValue<Int>>()
var z = x
while (z > 0) z -= how[z]!!.also { odd.add(it) }.value
val ans = IntArray(n)
fun place(list: List<IndexedValue<Int>>, start: Int, gap: Int) {
list.fold(start) { time, series -> (time + series.value * gap).also { ans[series.index] = time } }
}
place(odd, 1, 2)
place(groups[1] - odd, 2, 2)
place(groups[0], m - groupSum[0] + 1, 1)
println(ans.joinToString(" "))
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes8/FKt.class",
"javap": "Compiled from \"f.kt\"\npublic final class codeforces.kotlinheroes8.FKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround5/d.kt | package codeforces.globalround5
fun main() {
val n = readInt()
val a = readInts()
val b = a.plus(a).plus(a)
val st = SegmentsTreeSimple(b)
val r = IntArray(b.size)
val ans = IntArray(b.size)
for (i in b.indices.reversed()) {
val v = b[i]
var low = i + 1
var high = b.size + 1
while (low + 1 < high) {
val mid = (low + high) / 2
if (st.getMin(i + 1, mid) * 2 < v) {
high = mid
} else {
low = mid
}
}
r[i] = high - 1
if (i + 1 < b.size) {
r[i] = minOf(r[i], r[i + 1])
}
ans[i] = r[i] - i
if (r[i] == b.size) ans[i] = -1
}
print(ans.take(n).joinToString(" "))
}
class SegmentsTreeSimple(data: List<Int>) {
internal val min: IntArray
internal var size: Int = 1
init {
while (size <= data.size) size *= 2
min = IntArray(2 * size)
System.arraycopy(data.toIntArray(), 0, min, size, data.size)
for (i in size - 1 downTo 1) {
min[i] = minOf(min[2 * i], min[2 * i + 1])
}
}
internal fun getMin(from: Int, to: Int): Int {
var f = from + size
var t = to + size
var res = Integer.MAX_VALUE
while (f < t) {
if (f % 2 == 1) {
res = minOf(res, min[f])
f++
}
if (t % 2 == 1) {
t--
res = minOf(res, min[t])
}
f /= 2
t /= 2
}
return res
}
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround5/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.globalround5.DKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0... |
mikhail-dvorkin__competitions__3095312/codeforces/round614/b.kt | package codeforces.round614
import kotlin.math.abs
fun main() {
val (x0, y0, ax, ay, bx, by) = readLongs()
val (xs, ys, t) = readLongs()
val points = mutableListOf(x0 to y0)
while (true) {
val (x, y) = ax * points.last().first + bx to ay * points.last().second + by
if (xs + ys + t < x + y) break
points.add(x to y)
}
val best = points.indices.mapNotNull { i ->
points.indices.mapNotNull { j ->
(abs(j - i) + 1).takeIf { dist(xs to ys, points[i]) + dist(points[i], points[j]) <= t }
}.maxOrNull()
}.maxOrNull() ?: 0
println(best)
}
private fun dist(a: Pair<Long, Long>, b: Pair<Long, Long>): Long = abs(a.first - b.first) + abs(a.second - b.second)
private operator fun <E> List<E>.component6(): E = get(5)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readLongs() = readStrings().map { it.toLong() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round614/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round614.BKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readLongs:()Ljava/util/List;\n 3:... |
mikhail-dvorkin__competitions__3095312/codeforces/round614/c.kt | package codeforces.round614
fun main() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (a, b) = readInts().map { it - 1 }
nei[a].add(b); nei[b].add(a)
}
val par = List(n) { IntArray(n) { 0 } }
val count = List(n) { IntArray(n) { 1 } }
for (root in nei.indices) {
fun dfs(u: Int, p: Int) {
par[root][u] = p
for (v in nei[u]) if (v != p) {
dfs(v, u)
count[root][u] += count[root][v]
}
}
dfs(root, -1)
}
val a = List(n) { LongArray(n) { -1 } }
fun solve(u: Int, v: Int): Long {
if (u == v) return 0
if (a[u][v] == -1L) a[u][v] = maxOf(solve(par[v][u], v), solve(u, par[u][v])) + count[v][u] * count[u][v]
return a[u][v]
}
println(nei.indices.map { u -> nei.indices.maxOf { v -> solve(u, v) } }.maxOrNull())
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round614/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round614.CKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/round614/d.kt | package codeforces.round614
fun main() {
readLn()
val a = readInts()
val aCount = a.groupBy { it }.mapValues { it.value.size }
var b = aCount.keys.toList()
val (primes, factPrimes) = List(2) { MutableList(2) { listOf<Int>() } }
for (i in 2..b.maxOrNull()!!) {
val j = (2..i).first { i % it == 0 }
primes.add(primes[i / j].plus(j))
factPrimes.add(factPrimes[i - 1].plus(primes[i]).sortedDescending())
}
var ans = aCount.map { factPrimes[it.key].size * 1L * it.value }.sum()
for (x in factPrimes.last().indices) {
val groups = b.groupBy { factPrimes[it].getOrNull(x) }
val win = groups.mapValues { entry -> 2 * entry.value.sumOf { aCount.getValue(it) } - a.size }
val p = win.entries.firstOrNull { it.value > 0 }?.key ?: break
ans -= win.getValue(p)
b = groups.getValue(p)
}
println(ans)
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round614/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.round614.DKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/String;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/educationalround95/e.kt | package codeforces.educationalround95
fun main() {
val M = 998244353
val (n, m) = readInts()
val d = readInts().sorted()
val sum = d.sumOf { it.toLong() }
val ab = List(m) { readInts() }.withIndex().sortedBy { -it.value[1] }
var i = n - 1
var large = 0
var sumLarge = 0L
val ans = IntArray(m)
for (p in ab) {
val (a, b) = p.value
while (i >= 0 && d[i] >= b) {
large++
sumLarge += d[i]
i--
}
// val large = d.count { it >= b }
// val sumLarge = d.filter { it >= b }.sumOf { it.toLong() }
val sumSmall = sum - sumLarge
val pLarge = if (large == 0) 0 else (1 - minOf(a, large).toLong() * modInverse(large, M)) % M
val pSmall = (1 - minOf(a, large + 1).toLong() * modInverse(large + 1, M)) % M
ans[p.index] = (((sumLarge % M * pLarge + sumSmall % M * pSmall) % M + M) % M).toInt()
}
println(ans.joinToString("\n"))
}
fun gcdExtended(a: Int, b: Int, xy: IntArray): Int {
if (a == 0) {
xy[0] = 0
xy[1] = 1
return b
}
val d = gcdExtended(b % a, a, xy)
val t = xy[0]
xy[0] = xy[1] - b / a * xy[0]
xy[1] = t
return d
}
fun modInverse(x: Int, p: Int): Int {
val xy = IntArray(2)
val gcd = gcdExtended(x, p, xy)
require(gcd == 1) { "$x, $p" }
var result = xy[0] % p
if (result < 0) {
result += p
}
return result
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/educationalround95/EKt$main$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.educationalround95.EKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public codeforces.educa... |
mikhail-dvorkin__competitions__3095312/codeforces/polynomial2022/e_slow.kt | package codeforces.polynomial2022
fun main() {
val (n, d) = readInts()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v)
nei[v].add(u)
}
val arrays = List(2) { readInts().drop(1).map { it - 1 } }
val needed = List(2) { BooleanArray(n).also { it[0] = true } }
for (t in 0..1) {
for (x in arrays[t]) needed[t][x] = true
val stack = IntArray(n)
var stackSize = 0
fun dfs(v: Int, p: Int) {
stack[stackSize++] = v
if (needed[t][v] && stackSize > d) {
needed[t xor 1][stack[stackSize - 1 - d]] = true
}
for (u in nei[v]) if (u != p) {
dfs(u, v)
}
stackSize--
}
dfs(0, -1)
}
var ans = 0
for (t in 0..1) {
var travel = 0
fun dfs(v: Int, p: Int): Boolean {
var result = needed[t][v]
for (u in nei[v]) if (u != p) {
if (dfs(u, v)) result = true
}
if (result) travel++
return result
}
dfs(0, -1)
ans += (travel - 1) * 2
}
println(ans)
}
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/polynomial2022/E_slowKt.class",
"javap": "Compiled from \"e_slow.kt\"\npublic final class codeforces.polynomial2022.E_slowKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()L... |
mikhail-dvorkin__competitions__3095312/codeforces/polynomial2022/b_slow.kt | package codeforces.polynomial2022
import java.util.TreeSet
private fun solve(): String {
val (n, _, k) = readInts()
val a = readInts()
val allow = LongArray(n) { -1 }
val allowed = TreeSet<Long>()
fun encode(count: Int, index: Int) = (count.toLong() shl 32) + index.toLong()
for (i in a.indices) {
allowed.add(encode(a[i], i))
}
for (i in 0 until n) {
if (allow[i] >= 0) allowed.add(allow[i])
val use = allowed.pollLast() ?: return "NO"
val count = (use shr 32).toInt()
val index = use.toInt()
if (count > 1 && i + k < n) allow[i + k] = encode(count - 1, index)
}
return "YES"
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/polynomial2022/B_slowKt.class",
"javap": "Compiled from \"b_slow.kt\"\npublic final class codeforces.polynomial2022.B_slowKt {\n private static final java.lang.String solve();\n Code:\n 0: invokestatic #10 // Metho... |
mikhail-dvorkin__competitions__3095312/codeforces/polynomial2022/d.kt | package codeforces.polynomial2022
import java.lang.StringBuilder
private fun solve() {
val (hei, wid) = readInts()
val a = List(hei) { readInts() }
val aSum = a.map { it.sum() }.toIntArray()
val totalOnes = aSum.sum()
if (totalOnes % hei != 0) return println(-1)
val needOnes = totalOnes / hei
val ans = StringBuilder()
val donors = IntArray(hei)
val acceptors = IntArray(hei)
var ops = 0
for (x in 0 until wid) {
var donorsCount = 0
var acceptorsCount = 0
for (y in 0 until hei) {
if (aSum[y] == needOnes) continue
if (aSum[y] > needOnes && a[y][x] == 1) {
donors[donorsCount++] = y
}
if (aSum[y] < needOnes && a[y][x] == 0) {
acceptors[acceptorsCount++] = y
}
}
for (i in 0 until minOf(donorsCount, acceptorsCount)) {
aSum[donors[i]]--
aSum[acceptors[i]]++
ans.append("${donors[i] + 1} ${acceptors[i] + 1} ${x + 1}\n")
ops++
}
}
println(ops)
print(ans)
}
fun main() = repeat(readInt()) { solve() }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/polynomial2022/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.polynomial2022.DKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/Lis... |
mikhail-dvorkin__competitions__3095312/codeforces/deltix2021summer/b.kt | package codeforces.deltix2021summer
import kotlin.math.abs
private fun solve(a: List<Int>, first: Int): Long {
val aIndices = a.indices.filter { a[it] == 1 }
val neededIndices = a.indices.filter { it % 2 == 1 - first }
return aIndices.zip(neededIndices) { x, y -> abs(x - y).toLong() }.sum()
}
private fun solve(): Long {
readLn()
val a = readInts().map { it and 1 }
val n = a.size
val balance = a.sum() - n / 2
if (n % 2 == 0) {
if (balance == 0) return minOf(solve(a, 0), solve(a, 1))
} else {
if (balance in 0..1) return solve(a, balance)
}
return -1
}
fun main() {
repeat(readInt()) { println(solve()) }
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/deltix2021summer/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.deltix2021summer.BKt {\n private static final long solve(java.util.List<java.lang.Integer>, int);\n Code:\n 0: aload_0\n 1: checkcas... |
mikhail-dvorkin__competitions__3095312/codeforces/deltix2021summer/d.kt | package codeforces.deltix2021summer
fun ask(or: Boolean, i: Int, j: Int): Int {
val s = if (or) "or" else "and"
println("$s ${i + 1} ${j + 1}")
return readInt()
}
fun main() {
val (n, k) = readInts()
val (ands, ors) = List(2) { or -> List(n - 1) { ask(or == 1, 0, it + 1) } }
val and12 = ask(false, 1, 2)
val a = IntArray(n)
for (b in 0..29) {
val t = 1 shl b
val maybe0 = ands.all { (it and t) == 0 }
val maybe1 = ors.all { (it and t) == t }
val v = if (maybe1 && (!maybe0 || and12 and t == 0)) 1 else 0
a[0] = a[0] or (v * t)
for (i in 1 until n) {
val u = ((if (v == 1) ands[i - 1] else ors[i - 1]) shr b) and 1
a[i] = a[i] or (u * t)
}
}
a.sort()
println("finish ${a[k - 1]}")
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/deltix2021summer/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.deltix2021summer.DKt {\n public static final int ask(boolean, int, int);\n Code:\n 0: iload_0\n 1: ifeq 9\n 4: ldc ... |
mikhail-dvorkin__competitions__3095312/codeforces/deltix2021summer/f.kt | package codeforces.deltix2021summer
fun main() {
readLn()
val strengths = readInts().map { it.toModular() }
val n = strengths.size
val probWin = Array(n) { i -> Array(n) { j -> strengths[i] / (strengths[i] + strengths[j]) } }
val masks = 1 shl n
val pScc = Array(masks) { 1.toModular() }
var ans = 0.toModular()
for (mask in 1 until masks) {
if (mask.countOneBits() == 1) continue
var top = (mask - 1) and mask
var rest = 1L
while (top > 0) {
var thisTop = pScc[top]
for (i in 0 until n) {
if (!top.hasBit(i)) continue
for (j in 0 until n) {
if (top.hasBit(j) || !mask.hasBit(j)) continue
thisTop *= probWin[i][j]
}
}
if (mask == masks - 1) ans += top.countOneBits() * thisTop
rest -= thisTop.x
top = (top - 1) and mask
}
pScc[mask] = rest.toModular()
}
println(ans + n * pScc.last())
}
private fun Int.toModular() = Modular(this)//toDouble()
private fun Long.toModular() = Modular(this)
private class Modular {
companion object {
const val M = 1_000_000_007
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Long) { x = (value % M).toInt().let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
private fun Int.bit(index: Int) = shr(index) and 1
private fun Int.hasBit(index: Int) = bit(index) != 0
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/deltix2021summer/FKt.class",
"javap": "Compiled from \"f.kt\"\npublic final class codeforces.deltix2021summer.FKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/Str... |
mikhail-dvorkin__competitions__3095312/codeforces/round580/d.kt | package codeforces.round580
fun main() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (a, b) = readInts().map { it - 1 }
nei[a].add(b)
nei[b].add(a)
}
nei.indices.flatMap { v ->
val (sizes, vertices) = nei[v].map { Pair(dfs(it, setOf(v), 0, nei), it) }.sortedBy { it.first }.unzip()
sizes.indices.map { i ->
val size = sizes.take(i).sum()
Pair((size + 1) * (n - size)) { dfs(v, vertices.drop(i), 1, nei); dfs(v, vertices.take(i), size + 1, nei) }
}
}.maxByOrNull { it.first }?.second?.invoke()
}
private fun dfs(v: Int, p: Collection<Int>, k: Int, nei: List<List<Int>>): Int {
var sum = 1
for (u in nei[v].minus(p)) {
if (k > 0) println("${u + 1} ${v + 1} ${k * sum}")
sum += dfs(u, setOf(v), k, nei)
}
return sum
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round580/DKt$main$lambda$7$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.round580.DKt$main$lambda$7$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public codeforces.round58... |
mikhail-dvorkin__competitions__3095312/codeforces/round580/c.kt | package codeforces.round580
fun main() {
val n = readInt()
val a = List(n) { IntArray(n) }
a[0][0] = 1
propagate3(0, 1, 1, 2, a)
propagate3(1, 2, 1, 0, a)
for (i in a.indices) {
for (j in a.indices) {
if (i + j in setOf(0, 1, 2 * n - 2) || i == 1 && j == 2) continue
val ii = maxOf(i - 2, 0)
val jj = i + j - 2 - ii
propagate3(ii, jj, i, j, a)
}
}
val (b, c) = List(2) { t -> List(2 * n - 1) { val (x, y) = border(it, n); a[x][y] xor (t * it % 2) } }
val x = b.indices.first { x -> palindrome4(b, x) != palindrome4(c, x) }
val (x1, y1) = border(x, n)
val (x2, y2) = border(x + 3, n)
if (ask(x1, y1, x2, y2) != palindrome4(b, x)) {
for (i in a.indices) {
for (j in a.indices) {
a[i][j] = a[i][j] xor ((i + j) % 2)
}
}
}
println("!")
a.forEach { println(it.joinToString("")) }
}
private fun border(i: Int, n: Int) = if (i < n) Pair(0, i) else Pair(i - n + 1, n - 1)
private fun palindrome4(a: List<Int>, i: Int) = (a[i] == a[i + 3] && a[i + 1] == a[i + 2])
private fun propagate3(x1: Int, y1: Int, x2: Int, y2: Int, a: List<IntArray>) {
a[x2][y2] = a[x1][y1] xor if (ask(x1, y1, x2, y2)) 0 else 1
}
private fun ask(x1: Int, y1: Int, x2: Int, y2: Int): Boolean {
val output = setOf(listOf(x1, y1), listOf(x2, y2)).sortedBy { it.sum() }.flatten().map { it + 1 }
println("? ${output.joinToString(" ")}")
return readInt() == 1
}
private fun readInt() = readLine()!!.toInt()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round580/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round580.CKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/round783/b_wrong.kt | package codeforces.round783
import kotlin.math.sign
fun solve(a: List<Int>): Int {
val pref = mutableListOf(0L)
val prefIndex = mutableListOf(0)
val prefIndexRight = mutableListOf(0)
var prefSum = 0L
val dp = IntArray(a.size + 1)
for (i in a.indices) {
prefSum -= a[i]
dp[i + 1] = dp[i] + a[i].sign
if (prefSum > pref.last()) {
pref.add(prefSum)
prefIndex.add(i + 1)
prefIndexRight.add(i + 1)
continue
}
val bs = pref.binarySearch(prefSum)
if (bs >= 0) {
val j = prefIndexRight[bs]
dp[i + 1] = maxOf(dp[i + 1], dp[j])
prefIndexRight[bs] = i + 1
}
if (prefSum < pref.last()) {
val b = if (bs >= 0) bs + 1 else - 1 - bs
val j = prefIndex[b]
dp[i + 1] = maxOf(dp[i + 1], dp[j] + i + 1 - j)
}
if (pref.size >= 2 && prefSum > pref[pref.size - 2] && prefSum < pref.last() && dp[i + 1] - dp[prefIndex.last()] > i + 1 - prefIndex.last()) {
pref.removeLast()
prefIndex.removeLast()
prefIndexRight.removeLast()
pref.add(prefSum)
prefIndex.add(i + 1)
prefIndexRight.add(i + 1)
}
var improve = false
while (true) {
if (pref.isNotEmpty() && prefSum <= pref.last() && dp[i + 1] - dp[prefIndex.last()] > i + 1 - prefIndex.last()) {
pref.removeLast()
prefIndex.removeLast()
prefIndexRight.removeLast()
improve = true
continue
}
break
}
if (improve) {
pref.add(prefSum)
prefIndex.add(i + 1)
prefIndexRight.add(i + 1)
}
}
return dp.last()
}
private fun solve() {
readLn()
val a = readInts()
println(solve(a))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round783/B_wrongKt.class",
"javap": "Compiled from \"b_wrong.kt\"\npublic final class codeforces.round783.B_wrongKt {\n public static final int solve(java.util.List<java.lang.Integer>);\n Code:\n 0: aload_0\n 1: ldc ... |
mikhail-dvorkin__competitions__3095312/codeforces/round740/b.kt | package codeforces.round740
fun main() {
val (n, m) = readInts()
Modular.M = m
val primeDivisors = primeDivisors(n)
val a = Array(n + 1) { it.toModular() }
for (i in 3..n) {
a[i] = 1 + 2 * a[i - 1]
for (r in divisorsOf(i, primeDivisors)) {
if (r == 1 || r == i) continue
a[i] += a[r] - a[r - 1]
}
}
println(a.last())
}
fun divisorsOf(n: Int, primeDivisors: IntArray): IntArray {
if (n == 1) return intArrayOf(1)
val p = primeDivisors[n]
var m = n / p
var counter = 2
while (m % p == 0) {
m /= p
counter++
}
val divisorsOfM = divisorsOf(m, primeDivisors)
val result = IntArray(divisorsOfM.size * counter)
for (i in divisorsOfM.indices) {
var d = divisorsOfM[i]
for (j in 0 until counter) {
result[i * counter + j] = d
d *= p
}
}
return result
}
fun primeDivisors(n: Int): IntArray {
val primeDivisors = IntArray(n + 1) { it }
for (i in 2..n) {
if (primeDivisors[i] < i) continue
var j = i * i
if (j > n) break
do {
primeDivisors[j] = i
j += i
} while (j <= n)
}
return primeDivisors
}
private fun Int.toModular() = Modular(this)//toDouble()
private class Modular {
companion object {
var M: Int = 0
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round740/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round740.BKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/round572/c.kt | package codeforces.round572
private const val M = 998244353
private fun solve() {
val (n, m) = readInts()
val a = readInts().sorted()
val maxDiff = (a.last() - a.first()) / (m - 1)
val d = Array(m) { IntArray(n + 1) }
var ans = 0
for (diff in 1..maxDiff) {
var iPrev = 0
for (i in a.indices) {
while (a[i] - a[iPrev] >= diff) iPrev++
d[0][i + 1] = i + 1
for (j in 1 until m) {
d[j][i + 1] = (d[j][i] + d[j - 1][iPrev]) % M
}
}
ans = (ans + d[m - 1][n]) % M
}
println(ans)
}
fun main() {
val stdStreams = (false to true)
val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true"
if (!isOnlineJudge) {
if (!stdStreams.first) System.setIn(java.io.File("input.txt").inputStream())
if (!stdStreams.second) System.setOut(java.io.PrintStream("output.txt"))
}
val tests = if (isOnlineJudge) 1 else readInt()
repeat(tests) { solve() }
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round572/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round572.CKt {\n private static final int M;\n\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method read... |
mikhail-dvorkin__competitions__3095312/codeforces/round572/a2.kt | package codeforces.round572
private fun solve() {
val n = readInt()
val nei = List(n) { mutableListOf<Edge>() }
repeat(n - 1) {
val (aInput, bInput, value) = readInts()
val a = aInput - 1
val b = bInput - 1
nei[a].add(Edge(a, b, value))
nei[b].add(Edge(b, a, value))
}
if (nei.any { it.size == 2 }) {
println("NO")
return
}
println("YES")
val ans = nei.flatten().filter { it.from < it.to }.flatMap { edge ->
val a = dfs(edge.from, edge.to, false, nei)
val b = dfs(edge.from, edge.to, true, nei)
val c = dfs(edge.to, edge.from, false, nei)
val d = dfs(edge.to, edge.from, true, nei)
val halfValue = edge.value / 2
listOf(
Edge(a, c, halfValue),
Edge(b, d, halfValue),
Edge(a, b, -halfValue),
Edge(c, d, -halfValue)
).filter { it.from != it.to }
}
println(ans.size)
for (edge in ans) {
println("${edge.from + 1} ${edge.to + 1} ${edge.value}")
}
}
private data class Edge(val from: Int, val to: Int, val value: Int)
private fun dfs(v: Int, p: Int, order: Boolean, nei: List<List<Edge>>): Int {
if (nei[v].size == 1) return v
for (edge in (if (order) nei[v] else nei[v].reversed())) {
val u = edge.to
if (u == p) continue
return dfs(u, v, order, nei)
}
error("")
}
fun main() {
val stdStreams = (false to true)
val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true"
if (!isOnlineJudge) {
if (!stdStreams.first) System.setIn(java.io.File("input.txt").inputStream())
if (!stdStreams.second) System.setOut(java.io.PrintStream("output.txt"))
}
val tests = if (isOnlineJudge) 1 else readInt()
repeat(tests) { solve() }
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round572/A2Kt.class",
"javap": "Compiled from \"a2.kt\"\npublic final class codeforces.round572.A2Kt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/ozon2020/f.kt | package codeforces.ozon2020
import kotlin.random.Random
val r = Random(566)
fun main() {
readLn()
val a = readStrings().map { it.toLong() }.shuffled(r)
val toCheck = List(1 shl 6) { a[it % a.size] + r.nextInt(3) - 1 }.toSet()
val primes = toCheck.flatMap { primes(it) }.toSet().sorted()
val ans = primes.fold(a.size.toLong()) { best, p ->
a.foldRight(0L) { v, sum ->
(sum + if (v <= p) p - v else minOf(v % p, p - v % p))
.takeIf { it < best } ?: return@foldRight best
}
}
println(ans)
}
private fun primes(v: Long): List<Long> {
val primes = mutableListOf<Long>()
var x = v
for (i in 2..v) {
if (x < 2) break
if (i * i > x) {
primes.add(x)
break
}
while (x % i == 0L) {
primes.add(i)
x /= i
}
}
return primes
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/ozon2020/FKt.class",
"javap": "Compiled from \"f.kt\"\npublic final class codeforces.ozon2020.FKt {\n private static final kotlin.random.Random r;\n\n public static final kotlin.random.Random getR();\n Code:\n 0: getstatic #11... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/h.kt | package codeforces.kotlinheroes3
private fun solve() {
val s = readLn()
val inf = (s.maxOrNull()!! + 1).toString()
val init = listOf(listOf(inf to listOf<Boolean>()), listOf("" to listOf()))
val ans = s.foldIndexed(init) { i, (sure, unsure), c ->
val next = List(2) { MutableList(i + 1) { inf to listOf<Boolean>()} }
fun update(isSure: Boolean, index: Int, new: Pair<String, List<Boolean>>) {
val a = next[if (isSure) 0 else 1]
if (!new.first.startsWith(inf) && new.first < a[index].first) a[index] = new
}
sure.forEachIndexed { j, (t, how) ->
val storeShort = if (t.length == j) 1 else 0
update(true, j + 1 - storeShort, t to how + false)
update(true, minOf(j + storeShort, i - j), t + c to how + true)
}
unsure.forEachIndexed { j, (t, how) ->
update(false, j, t + c to how + true)
if (j != i - j && t != inf) when {
c > t[j] -> update(true, j + 1, t.substring(0, j) + c to how + true)
else -> update(c < t[j], j + 1, t to how + false)
}
}
next
}
println(ans.flatten().minByOrNull { it.first }!!.second.joinToString("") { if (it) "R" else "B" })
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/HKt.class",
"javap": "Compiled from \"h.kt\"\npublic final class codeforces.kotlinheroes3.HKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/String;... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/f.kt | package codeforces.kotlinheroes3
private fun solve() {
val (n, m) = readInts()
data class Segment(val start: Int, val end: Int, val id: Int)
val segments = List(n) { val data = readInts(); Segment(data[0], data[1], it) }
val byOpening = segments.sortedByDescending { it.start }.toMutableList()
val ans = MutableList(n) { 0 }
val byEnding = sortedSetOf<Segment>(compareBy({ it.end }, { it.id }))
var time = 0
var worstGap = 0
while (true) {
if (byEnding.isEmpty()) time = byOpening.lastOrNull()?.start ?: break
while (byOpening.lastOrNull()?.start == time) byEnding.add(byOpening.removeAt(byOpening.lastIndex))
for (temp in 0 until m) {
val segment = byEnding.pollFirst() ?: break
worstGap = maxOf(worstGap, time - segment.end)
ans[segment.id] = time
}
time++
}
println(worstGap)
println(ans.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/FKt$solve$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.kotlinheroes3.FKt$solve$$inlined$sortedByDescending$1<T> implements java.util.Comparator {\n public code... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/e.kt | package codeforces.kotlinheroes3
private fun solve() {
val (n, k) = readInts()
val nei = List(n) { mutableSetOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val leaves = nei.indices.filter { nei[it].size == 1 }.toMutableList()
if (k == 1) return println("Yes\n1\n1")
if (k > leaves.size) return println("No")
val ans = nei.indices.toMutableSet()
while (leaves.size > k) {
val v = leaves.last()
val u = nei[v].first()
ans.remove(v)
nei[u].remove(v)
leaves.removeAt(leaves.lastIndex)
if (nei[u].size == 1) leaves.add(u)
}
println("Yes\n${ans.size}\n${ans.map { it + 1 }.joinToString(" ")}")
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.kotlinheroes3.EKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/g.kt | package codeforces.kotlinheroes3
private val digits = 1..9
fun main() {
val (m, kIn) = readInts()
listOf(2, 3, 5, 7).fold(m) { acc, p ->
var temp = acc
while (temp % p == 0) temp /= p
temp
}.takeIf { it == 1 } ?: return println(-1)
val memo = mutableMapOf<Pair<Int, Int>, Long>()
fun count(m: Int, len: Int): Long {
if (len == 0) return if (m == 1) 1 else 0
val pair = m to len
memo[pair]?.let { return it }
val res = digits.filter { m % it == 0 }.map { count(m / it, len - 1) }.sum()
memo[pair] = res
return res
}
var k = kIn - 1L
val len = (1..m + kIn).first { len ->
val here = count(m, len)
if (k >= here) {
k -= here
false
} else true
}
var mm = m
val ans = List(len) { i ->
for (d in digits.filter { mm % it == 0 }) {
val here = count(mm / d, len - 1 - i)
if (k >= here) {
k -= here
continue
}
mm /= d
return@List d
}
}
return println(ans.joinToString(""))
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes3/GKt.class",
"javap": "Compiled from \"g.kt\"\npublic final class codeforces.kotlinheroes3.GKt {\n private static final kotlin.ranges.IntRange digits;\n\n public static final void main();\n Code:\n 0: invokestatic #1... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes4/i.kt | package codeforces.kotlinheroes4
fun main() {
val (n, m, _, sIn) = readInts()
val s = sIn - 1
val a = readInts()
val inf = n * n * n
val e = List(n) { IntArray(n) { inf } }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
e[u][v] = 1
}
for (k in e.indices) for (i in e.indices) for (j in e.indices) e[i][j] = minOf(e[i][j], e[i][k] + e[k][j])
val sum = List(1 shl n) { mask -> mask.oneIndices().sumOf { a[it].toLong() } }
val sumAll = sum.last()
val len = List(n) { List(n) { IntArray(1 shl n) { inf } } }
for (mask in 0 until (1 shl n)) {
val indices = mask.oneIndices()
if (indices.size == 1) len[indices[0]][indices[0]][mask] = 0
for (i in indices) for (j in indices) if (i != j) {
len[i][j][mask] = indices.minOf { k -> len[i][k][mask xor (1 shl j)] + e[k][j] }
}
}
val eat = List(n) { i ->
val map = java.util.TreeMap(mapOf(0L to 0, Long.MAX_VALUE to inf))
for (mask in sum.indices) if (mask.hasBit(i)) for (j in e.indices) if (mask.hasBit(j)) {
val eat = sum[mask]
val edges = len[i][j][mask]
if (map.ceilingEntry(eat)!!.value!! <= edges) continue
map[eat] = edges
while (true) {
val prevEntry = map.floorEntry(eat - 1) ?: break
if (prevEntry.value!! < edges) break
map.remove(prevEntry.key!!)
}
}
map
}
val best = mutableListOf(IntArray(n) { inf }.also { it[s] = 0 })
val seen = mutableMapOf<List<Int>, Pair<Int, Int>>()
val period: Int; val periodEdges: Int
while (true) {
val prev = best.last()
val next = IntArray(n) { i -> e.indices.minOf { j -> prev[j] + len[j][i].last() } }
best.add(next)
val nextMin = next.minOrNull()!!
val snapshot = next.map { it - nextMin }
if (snapshot in seen) {
period = seen.size - seen[snapshot]!!.first
periodEdges = nextMin - seen[snapshot]!!.second
break
}
seen[snapshot] = seen.size to nextMin
}
println(readLongs().map { c ->
val i = c / sumAll
val toTake = c - sumAll * i
val takePeriods = maxOf(i - best.size + period, 0) / period
val bestI = best[(i - takePeriods * period).toInt()]
takePeriods * periodEdges + e.indices.minOf { j -> bestI[j] + eat[j].ceilingEntry(toTake)!!.value!! }
}.joinToString("\n"))
}
private fun Int.bit(index: Int) = shr(index) and 1
private fun Int.hasBit(index: Int) = bit(index) != 0
private fun Int.oneIndices() = (0 until countSignificantBits()).filter { (this shr it) and 1 != 0 }
private fun Int.countSignificantBits() = Int.SIZE_BITS - Integer.numberOfLeadingZeros(this)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun readLongs() = readStrings().map { it.toLong() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes4/IKt.class",
"javap": "Compiled from \"i.kt\"\npublic final class codeforces.kotlinheroes4.IKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes4/g.kt | package codeforces.kotlinheroes4
private fun solve(p: List<Int>, x: List<Int>): List<Int>? {
val k = (0..x.size - 3).minByOrNull { x[it + 2] - x[it] }
?: return listOf(x[0], p[0], x[1], p[0])
for (i in k..k + 2) for (j in k until i) for (aPeriod in p) {
val rem = x[i] % aPeriod
if (x[j] % aPeriod != rem) continue
val other = x.filter { it % aPeriod != rem }
val gcd = other.zipWithNext(Int::minus).fold(0, ::gcd)
val bPeriod = p.firstOrNull { gcd % it == 0 } ?: continue
val bPhase = ((other.firstOrNull() ?: 0) + bPeriod - 1) % bPeriod + 1
val aPhase = (rem + aPeriod - 1) % aPeriod + 1
return listOf(aPhase, aPeriod, bPhase, bPeriod)
}
return null
}
fun main() {
readLn()
val ans = solve(readInts(), readInts().sorted()) ?: return println("NO")
println("YES\n${ans[0]} ${ans[1]}\n${ans[2]} ${ans[3]}")
}
private tailrec fun gcd(a: Int, b: Int): Int = if (a == 0) b else gcd(b % a, a)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes4/GKt.class",
"javap": "Compiled from \"g.kt\"\npublic final class codeforces.kotlinheroes4.GKt {\n private static final java.util.List<java.lang.Integer> solve(java.util.List<java.lang.Integer>, java.util.List<java.lang.Integer... |
mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes2/g.kt | package codeforces.kotlinheroes2
private fun solve() {
val n = readInt()
val flag = readInts()
val want = readInts()
val changed = flag.zip(want) { a, b -> a != b }
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (a, b) = readInts().map { it - 1 }
nei[a].add(b)
nei[b].add(a)
}
val w = changed.indexOfFirst { it }
if (w == -1) return println("Yes\n0")
val p = MutableList(n) { 0 }
val u = dfs(nei, p, changed, w, -1).second
val v = dfs(nei, p, changed, u, -1).second
val path = mutableListOf(v)
while (path.last() != u) path.add(p[path.last()])
println(check(flag, want, path) ?: check(flag, want, path.reversed()) ?: "No")
}
private fun check(flag: List<Int>, want: List<Int>, path: List<Int>): String? {
val f = flag.toMutableList()
val save = f[path.first()]
for ((a, b) in path.zipWithNext()) {
f[a] = f[b]
}
f[path.last()] = save
return "Yes\n${path.size}\n${path.map { it + 1 }.joinToString(" ")}".takeIf { f == want }
}
private fun dfs(nei: List<List<Int>>, p: MutableList<Int>, cool: List<Boolean>, v: Int, parent: Int): Pair<Int, Int> {
var best = if (cool[v]) 0 to v else -nei.size to -1
p[v] = parent
for (u in nei[v].minus(parent)) {
val (dist, vertex) = dfs(nei, p, cool, u, v)
if (dist + 1 > best.first) best = dist + 1 to vertex
}
return best
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/kotlinheroes2/GKt.class",
"javap": "Compiled from \"g.kt\"\npublic final class codeforces.kotlinheroes2.GKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: isto... |
mikhail-dvorkin__competitions__3095312/codeforces/round633/b.kt | package codeforces.round633
fun main() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val mark = BooleanArray(n)
val dist = IntArray(n)
fun dfs(v: Int) {
mark[v] = true
for (u in nei[v]) if (!mark[u]) {
dist[u] = dist[v] + 1
dfs(u)
}
}
dfs(0)
val leaves = nei.indices.filter { nei[it].size == 1 }
val differentParities = leaves.map { dist[it] % 2 }.toSet().size
val ansMin = if (differentParities == 1) 1 else 3
val ansMax = n - 1 - nei.indices.sumBy { v ->
val neiLeaves = nei[v].count { nei[it].size == 1 }
maxOf(neiLeaves - 1, 0)
}
println("$ansMin $ansMax")
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round633/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round633.BKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/round633/d.kt | package codeforces.round633
fun main() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val canTake = IntArray(n) { 1 }
val cannotTake = IntArray(n)
val canTakeAnswer = IntArray(n) { 1 }
val cannotTakeAnswer = IntArray(n)
fun dfs(v: Int, p: Int) {
nei[v].remove(p)
if (nei[v].isEmpty()) return
for (u in nei[v]) dfs(u, v)
val bestCanTake = nei[v].map { canTake[it] }.sortedDescending().take(2)
cannotTake[v] = nei[v].size - 1 + bestCanTake[0]
canTake[v] = maxOf(cannotTake[v], 1 + nei[v].maxOf { cannotTake[it] })
cannotTakeAnswer[v] = bestCanTake.sum() + nei[v].size - bestCanTake.size
canTakeAnswer[v] = maxOf(cannotTakeAnswer[v], canTake[v],
nei[v].maxOf { maxOf(canTakeAnswer[it], cannotTakeAnswer[it] + 1) })
}
val leaf = nei.indices.first { nei[it].size == 1 }
dfs(leaf, -1)
println(canTakeAnswer[leaf])
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round633/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.round633.DKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround8/e.kt | package codeforces.globalround8
private fun solve(out: List<MutableList<Int>>): String {
val layer = IntArray(out.size)
for (u in out.indices) {
if (layer[u] == 2) continue
for (v in out[u]) layer[v] = maxOf(layer[v], layer[u] + 1)
}
val ans = layer.indices.filter { layer[it] == 2 }
return "${ans.size}\n${ans.map { it + 1 }.joinToString(" ")}\n"
}
fun main() = repeat(readInt()) {
val (n, m) = readInts()
val out = List(n) { ArrayList<Int>(2) }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
out[u].add(v)
}
for (s in out.indices) out[s].sort()
output.append(solve(out))
}.also { println(output) }
val output = StringBuilder()
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround8/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.globalround8.EKt {\n private static final java.lang.StringBuilder output;\n\n private static final java.lang.String solve(java.util.List<? extends jav... |
mikhail-dvorkin__competitions__3095312/codeforces/round616/c.kt | package codeforces.round616
fun solve(k: Int, toSwitch: List<Int>, where: List<List<Int>>): List<Int> {
val p = MutableList(k) { it }
val odd = MutableList(k) { 0 }
val d = List(k) { mutableListOf(0, 1) }
fun get(x: Int): Int {
if (p[x] == x) return x
val par = p[x]
p[x] = get(par)
odd[x] = odd[x] xor odd[par]
return p[x]
}
fun spend(x: Int): Int {
if (where[x].isEmpty()) return 0
if (where[x].size == 1) {
val (a) = where[x]
val aa = get(a)
val old = d[aa].minOrNull()!!
d[aa][odd[a] xor toSwitch[x] xor 1] = k + 1
return d[aa].minOrNull()!! - old
}
val (a, b) = where[x].let { if ((x + it.hashCode()) % 2 == 0) it else it.reversed() }
val (aa, bb) = get(a) to get(b)
if (aa == bb) return 0
p[aa] = bb
odd[aa] = odd[a] xor odd[b] xor toSwitch[x]
val old = d[aa].minOrNull()!! + d[bb].minOrNull()!!
for (i in 0..1) {
d[bb][i] = minOf(d[bb][i] + d[aa][i xor odd[aa]], k + 1)
}
return d[bb].minOrNull()!! - old
}
var ans = 0
return toSwitch.indices.map { ans += spend(it); ans }
}
fun main() {
val (_, k) = readInts()
val toSwitch = readLn().map { '1' - it }
val where = List(toSwitch.size) { mutableListOf<Int>() }
repeat(k) { i ->
readLn()
readInts().forEach { where[it - 1].add(i) }
}
println(solve(k, toSwitch, where).joinToString("\n"))
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round616/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round616.CKt {\n public static final java.util.List<java.lang.Integer> solve(int, java.util.List<java.lang.Integer>, java.util.List<? extends java.util.Lis... |
mikhail-dvorkin__competitions__3095312/codeforces/round872/c_to_upsolve.kt | package codeforces.round872
import java.util.*
fun main() {
val n = readInt()
val a = readInts()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val price = IntArray(n)
val niceXor = IntArray(n)
val temp = TreeSet<Int>()
val nice = MutableList(n) { temp }
fun dfs(v: Int, p: Int) {
var kids = 0
for (u in nei[v]) if (u != p) {
dfs(u, v)
price[v] += price[u]
kids++
}
if (kids == 0) {
nice[v] = TreeSet<Int>().apply { add(a[v]) }
return
}
if (kids == 1) {
val u = nei[v].first { it != p }
nice[v] = nice[u]
niceXor[v] = niceXor[u] xor a[v]
return
}
val uu = nei[v].maxBy { nice[it].size }
val counter = TreeMap<Int, Int>()
for (u in nei[v]) if (u != p && u != uu) {
for (x in nice[u]) {
val y = x xor niceXor[u]
counter[y] = counter.getOrDefault(y, 0) + 1
}
}
val maxCount = counter.entries.maxOf { it.value }
val other = TreeSet(counter.filter { it.value == maxCount }.map { it.key })
val niceUU = nice[uu]
val niceXorUU = niceXor[uu]
fun unite(set1: TreeSet<Int>, xor1: Int, set2: TreeSet<Int>, xor2: Int) {
if (set1.size < set2.size) return unite(set2, xor2, set1, xor1)
val xor12 = xor1 xor xor2
val common = TreeSet<Int>()
for (x in set2) {
if (set1.contains(x xor xor12)) common.add(x xor xor2)
}
price[v] = kids - maxCount
if (common.isNotEmpty()) {
price[v]--
nice[v] = common
return
}
for (x in set2) {
set1.add(x xor xor12)
}
nice[v] = set1
niceXor[v] = xor1
}
unite(niceUU, niceXorUU, other, 0)
niceXor[v] = niceXor[v] xor a[v]
}
dfs(0, -1)
println(price[0])
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round872/C_to_upsolveKt.class",
"javap": "Compiled from \"c_to_upsolve.kt\"\npublic final class codeforces.round872.C_to_upsolveKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readIn... |
mikhail-dvorkin__competitions__3095312/codeforces/round680/a.kt | package codeforces.round680
private fun solve(): Long {
val (p, q) = readLongs()
if (p % q != 0L) return p
val xs = primeFactorization(q)
var ans = 1L
for (i in xs) {
var pp = p
while (pp % q == 0L && pp % i == 0L) pp /= i
if (pp % q != 0L) ans = maxOf(ans, pp)
}
return ans
}
fun primeFactorization(n: Long): LongArray {
var m = n
val tempLong = mutableListOf<Long>()
run {
var i: Long = 2
while (m > 1 && i * i <= m) {
while (m % i == 0L) {
tempLong.add(i)
m /= i
}
i++
}
}
if (m > 1) tempLong.add(m)
val factors = LongArray(tempLong.size)
for (i in factors.indices) {
factors[i] = tempLong[i]
}
return factors
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readLongs() = readStrings().map { it.toLong() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round680/AKt.class",
"javap": "Compiled from \"a.kt\"\npublic final class codeforces.round680.AKt {\n private static final long solve();\n Code:\n 0: invokestatic #10 // Method readLongs:()Ljava/util/List;\n ... |
mikhail-dvorkin__competitions__3095312/codeforces/codeton6/c.kt | package codeforces.codeton6
private fun solve() {
val (_, k) = readInts()
fun rightmost(a: List<Int>): IntArray {
val res = IntArray(k) { -1 }
for (i in a.indices) res[a[i]] = i
for (i in k - 2 downTo 0) res[i] = maxOf(res[i], res[i + 1])
return res
}
val a = readInts().map { it - 1 }
val present = BooleanArray(k)
for (x in a) present[x] = true
val right = rightmost(a)
val left = rightmost(a.asReversed()).map { a.size - 1 - it }
val ans = IntArray(k) {
if (right[it] == -1 || !present[it]) 0 else (right[it] - left[it] + 1) * 2
}
println(ans.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/codeton6/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.codeton6.CKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n 3... |
mikhail-dvorkin__competitions__3095312/codeforces/codeton6/e.kt | package codeforces.codeton6
import java.util.BitSet
private fun solve(): Int {
readln()
val a = readInts()
val highMex = (a.size + 1).takeHighestOneBit() * 2
val mark = IntArray(a.size + 1) { -1 }
val memo = List(highMex) { BitSet() }
val dp = mutableListOf(BitSet())
val (dpMax, dpSum) = List(2) { IntArray(a.size + 1) { 0 } }
dp[0][0] = true
dpSum[0] = 1
var leastAbsent = 1
for (i in a.indices) {
val dpCurrent = dp[i].clone() as BitSet
var mex = 0
for (j in i downTo 0) {
mark[a[j]] = i
if (a[j] == mex) {
while (mark[mex] == i) mex++
val t = (dpMax[j] or mex).takeHighestOneBit() * 2 - 1
if (leastAbsent > t) continue
val memoJ = memo[dpSum[j]]
if (memoJ[mex]) continue
memoJ[mex] = true
val dpJ = dp[j]
for (k in 0..dpMax[j]) if (dpJ[k]) dpCurrent[k xor mex] = true
while (dpCurrent[leastAbsent]) leastAbsent++
}
}
dp.add(dpCurrent)
dpSum[i + 1] = dpCurrent.cardinality()
dpMax[i + 1] = dpCurrent.length() - 1
}
return dpMax.last()
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/codeton6/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.codeton6.EKt {\n private static final int solve();\n Code:\n 0: invokestatic #12 // Method kotlin/io/ConsoleKt.readln:()Ljava/lan... |
mikhail-dvorkin__competitions__3095312/codeforces/codeton6/e_tl.kt | package codeforces.codeton6
private fun solve(): Int {
readln()
val a = readInts()
val mark = IntArray(a.size + 1) { -1 }
val dp0 = mutableSetOf(0)
val dp = MutableList(a.size + 1) { dp0 }
val dpMax = IntArray(a.size + 1) { 0 }
val dpHashCode = IntArray(a.size + 1) { 0 }
val used = mutableSetOf<Long>()
var leastAbsent = 1
for (i in a.indices) {
var mex = 0
val dpCurrent = dp[i].toMutableSet()
dp[i + 1] = dpCurrent
for (j in i downTo 0) {
val aj = a[j]
mark[aj] = i
if (aj == mex) {
while (mark[mex] == i) mex++
//println("${dp[j]} xor $mex}")
val t = dpMax[j] or mex
.let { (1 shl it.countSignificantBits()) - 1 }
if (leastAbsent > t) continue
val code = (dpHashCode[j].toLong() shl 32) or mex.toLong()
if (!used.add(code)) continue
for (v in dp[j]) dpCurrent.add(v xor mex)
while (leastAbsent in dpCurrent) leastAbsent++
}
}
dpMax[i + 1] = dpCurrent.max()
dpHashCode[i + 1] = dpCurrent.hashCode()
}
return dpMax.last()
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun Int.countSignificantBits() = Int.SIZE_BITS - Integer.numberOfLeadingZeros(this)
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/codeton6/E_tlKt.class",
"javap": "Compiled from \"e_tl.kt\"\npublic final class codeforces.codeton6.E_tlKt {\n private static final int solve();\n Code:\n 0: invokestatic #12 // Method kotlin/io/ConsoleKt.readln:()... |
mikhail-dvorkin__competitions__3095312/codeforces/codeton6/f.kt | package codeforces.codeton6
val toBaseArray = LongArray(Long.SIZE_BITS)
private fun solve(): Long {
val (n, k) = readLongs()
val threshold = (n + 1) / k
fun timesK(m: Long) = if (m <= threshold) m * k else n + 1
fun toBase(m: Long): Int {
var i = 0
var mm = m
do {
toBaseArray[i++] = mm % k
mm /= k
} while (mm > 0)
return i
}
val nLength = toBase(n)
fun lex(m: Long): Long {
val mLength = toBase(m)
var res = mLength.toLong()
var prefix = 0L
var ten = 1L
for (i in 0 until nLength) {
prefix = timesK(prefix) + toBaseArray.getOrElse(mLength - 1 - i) { 0 }
res += prefix - ten
ten *= k
}
return res
}
var ans = 0L
var ten = 1L
repeat(nLength) {
val searchHigh = timesK(ten)
val high = (ten - 1..searchHigh).binarySearch { lex(it) > it }
val low = (ten - 1..high).binarySearch { lex(it) >= it }
ans += high - low
ten = searchHigh
}
return ans
}
fun main() = repeat(readInt()) { println(solve()) }
private fun LongRange.binarySearch(predicate: (Long) -> Boolean): Long {
var (low, high) = this.first to this.last // must be false ... must be true
while (low + 1 < high) (low + (high - low) / 2).also { if (predicate(it)) high = it else low = it }
return high // first true
}
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readLongs() = readStrings().map { it.toLong() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/codeton6/FKt.class",
"javap": "Compiled from \"f.kt\"\npublic final class codeforces.codeton6.FKt {\n private static final long[] toBaseArray;\n\n public static final long[] getToBaseArray();\n Code:\n 0: getstatic #11 ... |
mikhail-dvorkin__competitions__3095312/codeforces/round626/b.kt | package codeforces.round626
fun main() {
readLn()
var a = readInts().sorted()
val powers = a.last().toString(2).length downTo 0
val ans = powers.sumBy { k ->
val two = 1 shl k
val res = (1..4).sumBy { countLess(a, it * two) } and 1
a = a.map { it and two - 1 }.sorted()
two * res
}
println(ans)
}
private fun countLess(a: List<Int>, value: Int): Int {
var j = a.lastIndex
return a.indices.sumBy { i ->
while (j >= 0 && a[i] + a[j] >= value) j--
minOf(i, j + 1)
}
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round626/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round626.BKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readLn:()Ljava/lang/String;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/round626/c.kt | package codeforces.round626
import java.io.*
private fun solve(): Long {
val (n, m) = readInts()
val c = readLongs()
val nei = List(n) { mutableListOf<Int>() }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
nei[v].add(u)
}
val hashed = nei.map { it.sorted().fold(1L) { acc: Long, x: Int -> acc * 566239L + x } }
val groups = hashed.indices.groupBy { hashed[it] }.map {
if (it.key == 1L) 0L else it.value.map { i -> c[i] }.sum()
}
return groups.fold(0L, ::gcd)
}
private tailrec fun gcd(a: Long, b: Long): Long = if (a == 0L) b else gcd(b % a, a)
fun main() = println(List(readInt()) { if (it > 0) readLn(); solve() }.joinToString("\n"))
private val `in` = BufferedReader(InputStreamReader(System.`in`))
private fun readLn() = `in`.readLine()
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun readLongs() = readStrings().map { it.toLong() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round626/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round626.CKt {\n private static final java.io.BufferedReader in;\n\n private static final long solve();\n Code:\n 0: invokestatic #10 ... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround20/f1.kt | package codeforces.globalround20
private fun solve() {
val n = readInt()
val a = readInts()
val count = IntArray(n + 1)
val pos = List(n + 1) { mutableListOf<Int>() }
for (i in a.indices) {
count[a[i]]++
pos[a[i]].add(i)
}
val often = count.indices.sortedBy { count[it] }
val mostOften = often.last()
val ans = IntArray(n) { -1 }
for (i in 0..often.size - 2) {
val v = often[i]
val u = often[i + 1]
for (j in 0 until count[v]) {
ans[pos[u][j]] = v
}
}
for (i in ans.indices) {
if (ans[i] == -1) ans[i] = mostOften
}
println(ans.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround20/F1Kt$solve$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.globalround20.F1Kt$solve$$inlined$sortedBy$1<T> implements java.util.Comparator {\n final int[] $count$inlined;\n... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround7/e.kt | package codeforces.globalround7
fun main() {
val n = readInt()
val p = readInts().map { it - 1 }
val q = readInts().map { it - 1 }
val pRev = IntArray(n)
for (i in p.indices) pRev[p[i]] = i
val st = SegmentsTreeSimple(2 * n)
var alive = n
val ans = q.map {
while (st.getMinBalance() >= 0) st[2 * n - 2 * pRev[--alive] - 1] = -1
st[2 * n - 2 * it - 2] = 1
alive
}
println(ans.map{ it + 1 }.joinToString(" "))
}
class SegmentsTreeSimple(var n: Int) {
var size = 2 * Integer.highestOneBit(n)
var min = IntArray(2 * size)
var sum = IntArray(2 * size)
operator fun set(index: Int, value: Int) {
var i = size + index
min[i] = minOf(0, value)
sum[i] = value
while (i > 1) {
i /= 2
min[i] = minOf(min[2 * i], sum[2 * i] + min[2 * i + 1])
sum[i] = sum[2 * i] + sum[2 * i + 1]
}
}
fun getMinBalance(): Int = min[1]
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround7/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.globalround7.EKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: istore_0... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround7/d.kt | package codeforces.globalround7
private fun solve() {
val s = readLn()
var i = 0
while (i < s.length - 1 - i && s[i] == s[s.length - 1 - i]) i++
println(s.take(i) + solve(s.drop(i).dropLast(i)) + s.takeLast(i))
}
private fun solve(s: String): String {
val n = s.length
val h = Hashing(s + s.reversed())
for (i in n downTo 0) {
if (h.hash(0, i) == h.hash(2 * n - i, 2 * n)) return s.take(i)
if (h.hash(n - i, n) == h.hash(n, n + i)) return s.takeLast(i)
}
error(s)
}
private const val M = 1_000_000_007
class Hashing(s: String, x: Int = 566239) {
val h = IntArray(s.length + 1)
val t = IntArray(s.length + 1)
fun hash(from: Int, to: Int): Int {
var res = ((h[to] - h[from] * t[to - from].toLong()) % M).toInt()
if (res < 0) res += M
return res
}
init {
t[0] = 1
for (i in s.indices) {
t[i + 1] = (t[i] * x.toLong() % M).toInt()
h[i + 1] = ((h[i] * x.toLong() + s[i].toLong()) % M).toInt()
}
}
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround7/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.globalround7.DKt {\n private static final int M;\n\n private static final void solve();\n Code:\n 0: invokestatic #10 // Met... |
mikhail-dvorkin__competitions__3095312/codeforces/round621/e.kt | package codeforces.round621
const val M = 1_000_000_007
fun main() {
val (n, m) = readInts()
val a = readInts().map { it - 1 }
val indices = List(n) { mutableListOf<Int>() }
for (x in a.indices) { indices[a[x]].add(x) }
val eaters = List(n) { mutableSetOf<Int>() }
repeat(m) {
val (id, hunger) = readInts().map { it - 1 }
eaters[id].add(hunger)
}
val eatable = List(2) { BooleanArray(n) { false } }
val count = List(2) { IntArray(n) { 0 } }
for (id in eaters.indices) {
for (hunger in eaters[id]) {
if (hunger < indices[id].size) {
eatable[0][indices[id][hunger]] = true
eatable[1][indices[id][indices[id].size - 1 - hunger]] = true
count[1][id]++
}
}
}
var max = 0
var waysMax = 1
for (v in count[1].filter { it > 0 }) {
max++
waysMax = ((waysMax.toLong() * v) % M).toInt()
}
for (x in a.indices) {
if (eatable[1][x]) count[1][a[x]]--
if (eatable[0][x]) count[0][a[x]]++ else continue
var cur = 0
var ways = 1
for (id in a.indices) {
val left = count[0][id]
val right = count[1][id]
val (two, one) = if (id == a[x]) {
(if (left - 1 < right) right - 1 else right) to 1
} else {
left * right - minOf(left, right) to left + right
}
val mul = if (two > 0) { cur += 2; two } else if (one > 0) { cur++; one } else continue
ways = ((ways.toLong() * mul) % M).toInt()
}
if (cur > max) {
max = cur; waysMax = ways
} else if (cur == max) {
waysMax = (waysMax + ways) % M
}
}
println("$max $waysMax")
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round621/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.round621.EKt {\n public static final int M;\n\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInt... |
mikhail-dvorkin__competitions__3095312/codeforces/round621/d.kt | package codeforces.round621
fun main() {
val (n, m, _) = readInts()
val special = readInts().map { it - 1 }
val nei = List(n) { mutableListOf<Int>() }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val (s, t) = listOf(0, n - 1).map { bfs(nei, it) }
val best = special.sortedBy { s[it] - t[it] }.fold(0 to -n) { (ans, maxPrev), i ->
maxOf(ans, maxPrev + t[i]) to maxOf(maxPrev, s[i])
}.first
println(minOf(t[0], best + 1))
}
private fun bfs(nei: List<MutableList<Int>>, s: Int): List<Int> {
val n = nei.size
val queue = mutableListOf(s)
val dist = MutableList(nei.size) { n }; dist[s] = 0
var low = 0
while (low < queue.size) {
val v = queue[low++]
for (u in nei[v]) {
if (dist[u] == n) {
dist[u] = dist[v] + 1
queue.add(u)
}
}
}
return dist
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round621/DKt.class",
"javap": "Compiled from \"d.kt\"\npublic final class codeforces.round621.DKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInts:()Ljava/util/List;\n 3: ... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround16/d.kt | package codeforces.globalround16
private fun solve() {
val (hei, wid) = readInts()
val a = readInts()
val places = mutableMapOf<Int, MutableList<Pair<Int, Int>>>()
val aSorted = a.sorted()
for (i in aSorted.indices) {
places.getOrPut(aSorted[i]) { mutableListOf() }.add(i / wid to i % wid)
}
places.forEach { (_, list) -> list.sortBy { - it.first * wid + it.second } }
val f = List(hei) { FenwickTree(wid) }
val ans = a.sumOf { v ->
val (x, y) = places[v]!!.removeLast()
f[x].sum(y).also { f[x].add(y, 1) }
}
println(ans)
}
class FenwickTree(n: Int) {
var t: LongArray
fun add(index: Int, value: Long) {
var i = index
while (i < t.size) {
t[i] += value
i += i + 1 and -(i + 1)
}
}
fun sum(index: Int): Long {
var i = index
var res: Long = 0
i--
while (i >= 0) {
res += t[i]
i -= i + 1 and -(i + 1)
}
return res
}
fun sum(start: Int, end: Int): Long {
return sum(end) - sum(start)
}
operator fun get(i: Int): Long {
return sum(i, i + 1)
}
operator fun set(i: Int, value: Long) {
add(i, value - get(i))
}
init {
t = LongArray(n)
}
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround16/DKt$solve$lambda$2$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.globalround16.DKt$solve$lambda$2$$inlined$sortBy$1<T> implements java.util.Comparator {\n final int $wid$in... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround16/f.kt | package codeforces.globalround16
private fun solve() {
val (_, m) = readInts()
val points = readInts().sorted()
val segments = List(m) { readInts().let { it[0] to it[1] } }
val groups = List(points.size + 1) { mutableListOf<Pair<Int, Int>>() }
for (segment in segments) {
val index = (-1..points.size).binarySearch { points[it] >= segment.first }
if (index < points.size && points[index] <= segment.second) continue
groups[index].add(segment)
}
var ifEats = 0L
var ifGives = 0L
val inf = Long.MAX_VALUE / 8
for (k in groups.indices) {
groups[k].sortBy { it.first }
val g = mutableListOf<Pair<Int, Int>>()
for (segment in groups[k]) {
if (g.isEmpty()) {
g.add(segment)
continue
}
if (g.last().first == segment.first && g.last().second <= segment.second) continue
while (g.isNotEmpty() && g.last().first <= segment.first && segment.second <= g.last().second) {
g.pop()
}
g.add(segment)
}
val pPrev = points.getOrElse(k - 1) { -inf }.toLong()
val pNext = points.getOrElse(k) { inf }.toLong()
var newIfEats = inf
var newIfGives = inf
for (i in 0..g.size) {
val comeLeft = g.getOrNull(i - 1)?.first?.toLong() ?: pPrev
val comeRight = g.getOrNull(i)?.second?.toLong() ?: pNext
val leftBest = minOf(ifEats + 2 * (comeLeft - pPrev), ifGives + comeLeft - pPrev)
val possibleIfEats = leftBest + pNext - comeRight
newIfEats = minOf(newIfEats, possibleIfEats)
val possibleIfGives = leftBest + 2 * (pNext - comeRight)
newIfGives = minOf(newIfGives, possibleIfGives)
}
ifEats = newIfEats
ifGives = newIfGives
}
println(minOf(ifEats, ifGives))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun IntRange.binarySearch(predicate: (Int) -> Boolean): Int {
var (low, high) = this.first to this.last // must be false ... must be true
while (low + 1 < high) (low + (high - low) / 2).also { if (predicate(it)) high = it else low = it }
return high // first true
}
private fun <T> MutableList<T>.pop() = removeAt(lastIndex)
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround16/FKt$solve$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class codeforces.globalround16.FKt$solve$$inlined$sortBy$1<T> implements java.util.Comparator {\n public codeforces.globalround16.FKt... |
mikhail-dvorkin__competitions__3095312/codeforces/globalround16/e.kt | package codeforces.globalround16
private fun solve() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (v, u) = readInts().map { it - 1 }
nei[v].add(u)
nei[u].add(v)
}
val kids = IntArray(n)
val isLeaf = BooleanArray(n)
val isBud = BooleanArray(n)
var ans = 0
fun dfs(v: Int, p: Int = -1) {
var nonLeaves = false
for (u in nei[v]) {
if (u == p) continue
dfs(u, v)
if (isBud[u]) continue
kids[v]++
if (!isLeaf[u]) nonLeaves = true
}
isLeaf[v] = (p != -1 && kids[v] == 0)
isBud[v] = (p != -1 && !nonLeaves && !isLeaf[v])
if (isBud[v]) ans--
if (isLeaf[v]) ans++
if (v == 0 && kids[v] == 0) ans++
}
dfs(0)
println(ans)
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/globalround16/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class codeforces.globalround16.EKt {\n private static final void solve();\n Code:\n 0: invokestatic #10 // Method readInt:()I\n 3: isto... |
mikhail-dvorkin__competitions__3095312/codeforces/round901/b.kt | package codeforces.round901
private fun precalc(mask: Int): IntArray {
val (a, b, m) = listOf(0x55, 0x33, 0x0F).map { it and mask }
val source = a with b
val queue = mutableListOf<Int>()
val dist = IntArray(1 shl 14) { -1 }
queue.add(source)
dist[source] = 0
var low = 0
while (low < queue.size) {
val v = queue[low++]
fun move(xx: Int, yy: Int) {
val u = xx with yy
if (dist[u] != -1) return
dist[u] = dist[v] + 1
queue.add(u)
}
val (x, y) = decode(v)
move(x and y, y)
move(x or y, y)
move(x, y xor x)
move(x, y xor m)
}
return dist
}
private val precalc = List(128) { precalc(it) }
private fun solve(): Int {
val (a, b, c, d, m) = readInts()
var mask = 128; var cWant = 0; var dWant = 0
for (i in 0 until Int.SIZE_BITS) {
val type = 7 - a[i] - (b[i] shl 1) - (m[i] shl 2)
if (mask[type] == 1) {
if (c[i] != cWant[type] || d[i] != dWant[type]) return -1
continue
}
mask = mask.setBit(type)
if (c[i] == 1) cWant = cWant.setBit(type)
if (d[i] == 1) dWant = dWant.setBit(type)
}
return precalc[mask - 128][cWant with dWant]
}
fun main() = repeat(readInt()) { println(solve()) }
private infix fun Int.with(that: Int) = shl(7) or that
fun decode(code: Int) = (code ushr 7) to (code and 0x7F)
private fun Int.bit(index: Int) = ushr(index) and 1
private fun Int.setBit(index: Int) = or(1 shl index)
private operator fun Int.get(index: Int) = bit(index)
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round901/BKt.class",
"javap": "Compiled from \"b.kt\"\npublic final class codeforces.round901.BKt {\n private static final java.util.List<int[]> precalc;\n\n private static final int[] precalc(int);\n Code:\n 0: iconst_3\n 1... |
mikhail-dvorkin__competitions__3095312/codeforces/round901/d_ok_but_should_be_wa.kt | package codeforces.round901
private fun solve(): Double {
val (n, m) = readInts()
val d = List(n + 1) { DoubleArray(m - n + 1) }
for (i in 1..n) {
var kBest = 0
for (s in d[i].indices) {
val range = maxOf(kBest - 5, 0)..minOf(kBest + 11, s)
var best = Double.MAX_VALUE
for (k in range) {
val new = (i + s - 1.0 - k) / (1 + k) + d[i - 1][s - k]
if (new < best) {
best = new
kBest = k
}
}
d[i][s] = best
}
}
return d[n][m - n] * 2 + n
}
fun main() = repeat(1) { println(solve()) }
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round901/D_ok_but_should_be_waKt.class",
"javap": "Compiled from \"d_ok_but_should_be_wa.kt\"\npublic final class codeforces.round901.D_ok_but_should_be_waKt {\n private static final double solve();\n Code:\n 0: invokestatic #10 ... |
mikhail-dvorkin__competitions__3095312/codeforces/round901/b_slow.kt | package codeforces.round901
private fun solve() {
fun encode(a: Int, b: Int) = (a.toLong() shl 32) or b.toLong()
val (a, b, c, d, m) = readIntArray()
val source = encode(a, b)
val dest = encode(c, d)
val queue = mutableListOf<Long>()
val dist = mutableMapOf<Long, Int>()
queue.add(source)
dist[source] = 0
var low = 0
while (low < queue.size && dest !in dist) {
val v = queue[low]
val di = dist[v]!! + 1
low++
fun move(xx: Int, yy: Int) {
val u = encode(xx, yy)
if (u in dist) return
dist[u] = di
queue.add(u)
}
val x = (v shr 32).toInt()
val y = v.toInt()
move(x and y, y)
move(x or y, y)
move(x, y xor x)
move(x, y xor m)
}
val ans = dist[dest] ?: -1
out.appendLine(ans.toString())
}
fun main() = repeat(readInt()) { solve() }.also { out.close() }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun readIntArray() = readln().parseIntArray()
private fun readLongs() = readStrings().map { it.toLong() }
private fun String.parseIntArray(): IntArray {
val result = IntArray(count { it == ' ' } + 1)
var i = 0; var value = 0
for (c in this) {
if (c != ' ') {
value = value * 10 + c.code - '0'.code
continue
}
result[i++] = value
value = 0
}
result[i] = value
return result
}
private val `in` = System.`in`.bufferedReader()
private val out = System.out.bufferedWriter()
private fun readln() = `in`.readLine()
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round901/B_slowKt.class",
"javap": "Compiled from \"b_slow.kt\"\npublic final class codeforces.round901.B_slowKt {\n private static final java.io.BufferedReader in;\n\n private static final java.io.BufferedWriter out;\n\n private static f... |
mikhail-dvorkin__competitions__3095312/codeforces/round901/c.kt | package codeforces.round901
private fun precalc(n: Int = 5000): List<DoubleArray> {
val p = List(n + 1) { DoubleArray(it) }
for (i in 1..n) {
p[i][0] = 1.0 / i
for (j in 1 until i) {
if (j >= 2) p[i][j] = (j - 1.0) / i * p[i - 2][j - 2]
if (j < i - 1) p[i][j] += (i - j - 1.0) / i * p[i - 2][j - 1]
}
}
return p
}
private val precalc = precalc()
private fun solve(): Double {
val (n, m) = readInts()
val nei = List(n) { mutableListOf<Int>() }
repeat(m) {
val (a, b) = readInts().map { it - 1 }
nei[a].add(b)
}
val p = DoubleArray(n)
p[n - 1] = 1.0
for (i in n - 2 downTo 0) {
val ps = nei[i].map { p[it] }.sortedDescending()
p[i] = ps.indices.sumOf { j -> ps[j] * precalc[ps.size][j] }
}
return p[0]
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| [
{
"class_path": "mikhail-dvorkin__competitions__3095312/codeforces/round901/CKt.class",
"javap": "Compiled from \"c.kt\"\npublic final class codeforces.round901.CKt {\n private static final java.util.List<double[]> precalc;\n\n private static final java.util.List<double[]> precalc(int);\n Code:\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.