Advertisement
nachtvaohal

prefix-hash

Jan 23rd, 2024 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.90 KB | None | 0 0
  1. import java.util.StringTokenizer
  2.  
  3. class PrefixHash(
  4.     private val string: String,
  5.     private val base: Int,
  6.     private val modulus: Int
  7. ) {
  8.     private val powers: LongArray
  9.     private val hashes: LongArray
  10.  
  11.     init {
  12.         powers = initPowers()
  13.         hashes = initHashes()
  14.     }
  15.  
  16.     /**
  17.      * 1 <= [start] <= [end] <= [string.length]
  18.      *
  19.      * @param start inclusive
  20.      * @param end inclusive
  21.      */
  22.     fun getSubstringHash(start: Int, end: Int): Long {
  23.         return (hashes[end] - hashes[start - 1]) * powers[string.length - start] % modulus
  24.     }
  25.  
  26.     private fun initPowers() : LongArray {
  27.         // power to (base ^ power) % modulus
  28.         val p = LongArray(string.length + 1)
  29.         p[0] = 1
  30.         for (i in 1..string.length) {
  31.             p[i] = (p[i - 1] * base) % modulus
  32.         }
  33.         return p
  34.     }
  35.  
  36.     private fun initHashes(): LongArray {
  37.         val h = LongArray(string.length + 1)
  38.         h[0] = 0L
  39.         for (i in 1..string.length) {
  40.             h[i] = (h[i - 1] * base + string[i - 1].code) % modulus
  41.         }
  42.         return h
  43.     }
  44. }
  45.  
  46. fun main() {
  47.     val reader = System.`in`.bufferedReader()
  48.     val writer = System.out.bufferedWriter()
  49.  
  50.     val base = reader.readLine().toInt()
  51.     val modulus = reader.readLine().toInt()
  52.     val string = reader.readLine()
  53.     val count = reader.readLine().toInt()
  54.  
  55.     val substringIndexes = Array(count) {
  56.         val tokenizer = StringTokenizer(reader.readLine())
  57.         Pair(tokenizer.nextToken().toInt(), tokenizer.nextToken().toInt())
  58.     }
  59.     val stringHashContainer = PrefixHash(string, base, modulus)
  60.  
  61.     with(writer) {
  62.         substringIndexes
  63.             .forEach {
  64.                 val substringHash = stringHashContainer.getSubstringHash(it.first, it.second)
  65.                 write(substringHash.toString())
  66.                 newLine()
  67.             }
  68.         flush()
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement