为什么 Kotlin 代码会 MLE 后三个点

P3372 【模板】线段树 1

Mr_罗 @ 2024-10-01 12:53:07

RT。

import java.util.Scanner

class SegTree(val n: Int) {
    val su = Array<Long>(n shl 2) { 0 }
    val tg = Array<Long>(n shl 2) { 0 }

    fun psu(i: Int) {
        su[i] = su[i shl 1] + su[i shl 1 or 1]
    }

    fun psd(i: Int, l: Int, r: Int, k: Long) {
        su[i] += k * (r - l + 1); tg[i] += k
    }

    fun psd(i: Int, l: Int, r: Int) {
        val k = tg[i]; if (k != 0L) {
            val mid = l + r shr 1
            psd(i shl 1, l, mid, k); psd(i shl 1 or 1, mid + 1, r, k)
            tg[i] = 0
        }
    }

    fun modify(L: Int, R: Int, k: Long, i: Int = 1, l: Int = 1, r: Int = n) {
        if (L <= l && r <= R) {
            psd(i, l, r, k); return
        }
        psd(i, l, r); val mid = l + r shr 1
        if (L <= mid) modify(L, R, k, i shl 1, l, mid)
        if (mid < R) modify(L, R, k, i shl 1 or 1, mid + 1, r)
        psu(i)
    }

    fun query(L: Int, R: Int, i: Int = 1, l: Int = 1, r: Int = n): Long {
        if (L <= l && r <= R) return su[i]
        psd(i, l, r); val mid = l + r shr 1; var res = 0L
        if (L <= mid) res += query(L, R, i shl 1, l, mid)
        if (mid < R) res += query(L, R, i shl 1 or 1, mid + 1, r)
        return res
    }
}

fun main() {
    val read = Scanner(System.`in`)
    val n = read.nextInt(); val m = read.nextInt()
    val T = SegTree(n)
    var a: Long
    for (i in 1 .. n) {
        a = read.nextLong(); T.modify(i, i, a)
    }
    var op: Int; var l: Int; var r: Int; var k: Long
    for (i in 1 .. m) {
        op = read.nextInt(); l = read.nextInt(); r = read.nextInt()
        if (op == 1) {
            k = read.nextLong()
            T.modify(l, r, k)
        }
        else println(T.query(l, r))
    }
}

|