Advertisement
vkazar

Untitled

Oct 31st, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.32 KB | None | 0 0
  1. package sprint4.final
  2.  
  3. import java.io.BufferedReader
  4. import java.io.InputStreamReader
  5. import java.util.*
  6.  
  7. class MyHashTable {
  8.     private val capacity = 100003
  9.     private val innerArray: MutableList<Bucket?> = MutableList(capacity) { null }
  10.     private val modifier = Int.MAX_VALUE / 2
  11.  
  12.     operator fun set(key: Int, value: Int) {
  13.         innerArray[getIndex(key)] = Bucket(value, key)
  14.     }
  15.  
  16.     operator fun get(key: Int) = innerGet(key)?.value
  17.  
  18.     fun delete(key: Int) = innerGet(key)?.delete()
  19.  
  20.     private fun innerGet(key: Int): Bucket? = innerArray[getIndex(key)]?.takeIf { !it.deleted }
  21.  
  22.     private fun getIndex(key: Int): Int {
  23.  
  24.         var step = 0
  25.  
  26.         while (true) {
  27.             val secondHash = (key / 2)
  28.                 .let {
  29.                     it + if (key % 2 == it % 2) {
  30.                         1
  31.                     } else {
  32.                         0
  33.                     }
  34.                 }
  35.             val candidateIndex: Int = (key % capacity + modifier + (secondHash * step) % capacity) % capacity
  36.             val candidateBucket = innerArray[candidateIndex] ?: return candidateIndex
  37.             if (candidateBucket.deleted || candidateBucket.key != key) {
  38.                 ++step
  39.                 continue
  40.             }
  41.             return candidateIndex
  42.         }
  43.     }
  44.  
  45.     private class Bucket constructor(val value: Int, val key: Int) {
  46.         var deleted = false
  47.             private set
  48.  
  49.         fun delete(): Int {
  50.             deleted = true
  51.             return value
  52.         }
  53.     }
  54. }
  55.  
  56. fun main() {
  57.     val buffer = BufferedReader(InputStreamReader(System.`in`))
  58.     val sb = StringBuilder()
  59.     val hashTable = MyHashTable()
  60.     repeat(buffer.readLine().toInt()) {
  61.         val tokenizer = StringTokenizer(buffer.readLine())
  62.         when (tokenizer.nextToken()) {
  63.             "get" -> hashTable[tokenizer.nextToken().toInt()].nullSafeToString()
  64.             "put" -> {
  65.                 hashTable[tokenizer.nextToken().toInt()] = tokenizer.nextToken().toInt()
  66.                 null
  67.             }
  68.             "delete" -> hashTable.delete(tokenizer.nextToken().toInt()).nullSafeToString()
  69.             else -> throw Error("unknown command")
  70.         }
  71.             ?.let { sb.appendLine(it) }
  72.     }
  73.     println(sb)
  74. }
  75.  
  76. fun Int?.nullSafeToString() = this?.toString() ?: "None"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement