fun createLIS(permutation: List): List { val minLast = IntArray(permutation.size + 1){permutation.size + 1}.also { it[0] = 0 } val prevValue = IntArray(permutation.size + 1) for (a in permutation) { val pos = minLast.lowerBound(a) prevValue[a] = minLast[pos - 1] minLast[pos] = a } val result = mutableListOf((minLast.last { it != permutation.size + 1 })) while (result.last() > 0) { result.add(prevValue[result.last()]) } result.removeLast() return result.reversed() } inline fun IntArray.partitionPoint(predicate: (Int) -> Boolean): Int { var min = 0 var max = size while (min < max) { val mid = (min + max) / 2 if (predicate(this[mid])) { min = mid + 1 }else { max = mid } } return max } fun IntArray.lowerBound(target: Int): Int { return partitionPoint { it < target } } fun main() { System.setProperty("kotlin.collections.convert_arg_to_set_in_removeAll", "true") val n = readLine()!!.trim().toInt() val permutation = readLine()!!.trim().split(' ').map(String::toInt) val forward = createLIS(permutation) val backward = createLIS(permutation.reversed().map { n - it + 1 }).reversed().map { n - it + 1 } val fix = forward.intersect(backward) println(fix.size) println(fix.toList().sorted().joinToString(" ")) }