Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader
- import java.io.File
- // <template>
- class Node(var left: Node?, var right: Node?, var value: Int)
- // <template>
- private val counter = mutableMapOf<Int, Int>()
- fun main() {
- val reader = File("input.txt").inputStream().bufferedReader()
- val writer = File("output.txt").outputStream().bufferedWriter()
- val treeReader = TreeReader<Node> { v, l, r -> Node(l, r, v) }
- val root = treeReader.readTree(reader)
- val res = printRange(root, 1, 1000)
- res.sorted().forEach { writer.appendLine(it.toString()) }
- val diffs = treeReader.counter.filter { counter[it.key] != it.value }.toMap()
- println(diffs)
- }
- fun printRange(root: Node?, L: Int, R: Int):List<Int> {
- if (root == null) return listOf()
- val res = mutableListOf<Int>()
- fun getValuesInRange(node: Node?, L: Int, R: Int) {
- if (node == null) return
- if (L <= node.value) {
- getValuesInRange(node.left, L, R)
- }
- if (node.value in L..R) {
- counter[node.value] = counter.getOrDefault(node.value, 0) + 1
- res.add(node.value)
- }
- if (R >= node.value) {
- getValuesInRange(node.right, L, R)
- }
- }
- getValuesInRange(root, L, R)
- return res
- }
- class TreeReader<T>(private val nodeCreator: (Int, T?, T?) -> T?) {
- private val _counter = mutableMapOf<Int, Int>()
- val counter: Map<Int, Int>
- get() = _counter.toMap()
- fun readTree(reader: BufferedReader): T? {
- return reader.use { buffer ->
- val count = buffer.readLine().toInt()
- buildMap {
- repeat(count) {
- val line = buffer.readLine().split(" ")
- val id = line[0].toInt()
- val value = line[1].toInt()
- _counter[value] = _counter.getOrDefault(value, 0) + 1
- put(id, value to (line[2] to line[3]))
- }
- }.createTree()
- }
- }
- private fun Map<Int, Pair<Int, Pair<String, String>>>.createTree(): T? = createNode(this.keys.min())
- private fun Map<Int, Pair<Int, Pair<String, String>>>.createNode(id: Int): T? {
- val value = this[id] ?: return null
- val childrenIds = value.second
- return nodeCreator(
- value.first,
- childrenIds.first.toIntOrNull()?.let { createNode(it) },
- childrenIds.second.toIntOrNull()?.let { createNode(it) })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement