Permutation Separation (Codeforces 1295E)
Tags: Others, divide and conquer

You are given a permutation $$$p_1, p_2, \dots , p_n$$$ (an array where each integer from $$$1$$$ to $$$n$$$ appears exactly once). The weight of the $$$i$$$-th element of this permutation is $$$a_i$$$.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements $$$p_1, p_2, \dots , p_k$$$, the second — $$$p_{k+1}, p_{k+2}, \dots , p_n$$$, where $$$1 \le k < n$$$.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay $$$a_i$$$ dollars to move the element $$$p_i$$$.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if $$$p = [3, 1, 2]$$$ and $$$a = [7, 1, 4]$$$, then the optimal strategy is: separate $$$p$$$ into two parts $$$[3, 1]$$$ and $$$[2]$$$ and then move the $$$2$$$-element into first set (it costs $$$4$$$). And if $$$p = [3, 5, 1, 6, 2, 4]$$$, $$$a = [9, 1, 9, 9, 1, 9]$$$, then the optimal strategy is: separate $$$p$$$ into two parts $$$[3, 5, 1]$$$ and $$$[6, 2, 4]$$$, and then move the $$$2$$$-element into first set (it costs $$$1$$$), and $$$5$$$-element into second set (it also costs $$$1$$$).Calculate the minimum number of dollars you have to spend.

Input: The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of permutation.The second line contains $$$n$$$ integers $$$p_1, p_2, \dots , p_n$$$ ($$$1 \le p_i \le n$$$). It's guaranteed that this sequence contains each element from $$$1$$$ to $$$n$$$ exactly once.The third line contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Output: Print one integer — the minimum number of dollars you have to spend.


Sample Inputs:
3
3 1 2
7 1 4

4
2 4 1 3
5 9 8 3

6
3 5 1 6 2 4
9 1 9 9 1 9

Sample Outputs:
4

3

2

Solution (Python):
def main():
    import sys
    input = sys.stdin.buffer.readline
    N = int(input())
    P = list(map(int, input().split()))
    A = list(map(float, input().split()))

    class LazySegTree:

        def __init__(self, A, initialize=True, segfunc=min, ident=2000000000):
            self.N = len(A)
            self.LV = (self.N - 1).bit_length()
            self.N0 = 1 << self.LV
            self.segfunc = segfunc
            self.ident = ident
            if initialize:
                self.data = [self.ident] * self.N0 + A + [self.ident] * (self.N0 - self.N)
                for i in range(self.N0 - 1, 0, -1):
                    self.data[i] = segfunc(self.data[i * 2], self.data[i * 2 + 1])
            else:
                self.data = [self.ident] * (self.N0 * 2)
            self.lazy = [0] * (self.N0 * 2)

        def _ascend(self, i):
            for _ in range(i.bit_length() - 1):
                i >>= 1
                self.data[i] = self.segfunc(self.data[i * 2], self.data[i * 2 + 1]) + self.lazy[i]

        def _descend(self, idx):
            lv = idx.bit_length()
            for j in range(lv - 1, 0, -1):
                i = idx >> j
                x = self.lazy[i]
                if not x:
                    continue
                self.lazy[i] = 0
                self.lazy[i * 2] += x
                self.lazy[i * 2 + 1] += x
                self.data[i * 2] += x
                self.data[i * 2 + 1] += x

        def add(self, l, r, x):
            l += self.N0 - 1
            r += self.N0 - 1
            l_ori = l
            r_ori = r
            while l < r:
                if l & 1:
                    self.data[l] += x
                    self.lazy[l] += x
                    l += 1
                if r & 1:
                    r -= 1
                    self.data[r] += x
                    self.lazy[r] += x
                l >>= 1
                r >>= 1
            self._ascend(l_ori // (l_ori & -l_ori))
            self._ascend(r_ori // (r_ori & -r_ori) - 1)

        def query(self, l, r):
            l += self.N0 - 1
            r += self.N0 - 1
            self._descend(l // (l & -l))
            self._descend(r // (r & -r) - 1)
            ret = self.ident
            while l < r:
                if l & 1:
                    ret = self.segfunc(ret, self.data[l])
                    l += 1
                if r & 1:
                    ret = self.segfunc(self.data[r - 1], ret)
                    r -= 1
                l >>= 1
                r >>= 1
            return ret
    p2i = {}
    for (i, p) in enumerate(P):
        p2i[p] = i
    S = 0
    init = [0.0] * N
    for i in range(1, N):
        S += A[i - 1]
        init[i - 1] = S
    segtree = LazySegTree(init, ident=float('inf'))
    ans = A[0]
    cnt = 0
    for p in range(1, N + 1):
        i = p2i[p]
        a = A[i]
        cnt += a
        segtree.add(i + 1, N, -a * 2)
        ans = min(ans, segtree.query(1, N) + cnt)
    print(int(ans))
if __name__ == '__main__':
    main()

Solution (Python):
from operator import add

class LazySegmentTree:

    def __init__(self, n, init, merge=min, merge_unit=10 ** 18, operate=add, operate_unit=0):
        self.merge = merge
        self.merge_unit = merge_unit
        self.operate = operate
        self.operate_unit = operate_unit
        self.n = (n - 1).bit_length()
        self.data = [0 for i in range(1 << self.n + 1)]
        self.lazy = [0 for i in range(1 << self.n + 1)]
        for i in range(n):
            self.data[2 ** self.n + i] = init[i]
        for i in range(2 ** self.n - 1, 0, -1):
            self.data[i] = self.merge(self.data[2 * i], self.data[2 * i + 1])

    def propagate_above(self, i):
        m = i.bit_length() - 1
        for bit in range(m, 0, -1):
            v = i >> bit
            add = self.lazy[v]
            self.lazy[v] = 0
            self.data[2 * v] = self.operate(self.data[2 * v], add)
            self.data[2 * v + 1] = self.operate(self.data[2 * v + 1], add)
            self.lazy[2 * v] = self.operate(self.lazy[2 * v], add)
            self.lazy[2 * v + 1] = self.operate(self.lazy[2 * v + 1], add)

    def remerge_above(self, i):
        while i:
            i >>= 1
            self.data[i] = self.operate(self.merge(self.data[2 * i], self.data[2 * i + 1]), self.lazy[i])

    def update(self, l, r, x):
        l += 1 << self.n
        r += 1 << self.n
        l0 = l // (l & -l)
        r0 = r // (r & -r) - 1
        while l < r:
            if l & 1:
                self.data[l] = self.operate(self.data[l], x)
                self.lazy[l] = self.operate(self.lazy[l], x)
                l += 1
            if r & 1:
                self.data[r - 1] = self.operate(self.data[r - 1], x)
                self.lazy[r - 1] = self.operate(self.lazy[r - 1], x)
            l >>= 1
            r >>= 1
        self.remerge_above(l0)
        self.remerge_above(r0)

    def query(self, l, r):
        l += 1 << self.n
        r += 1 << self.n
        l0 = l // (l & -l)
        r0 = r // (r & -r) - 1
        self.propagate_above(l0)
        self.propagate_above(r0)
        res = self.merge_unit
        while l < r:
            if l & 1:
                res = self.merge(res, self.data[l])
                l += 1
            if r & 1:
                res = self.merge(res, self.data[r - 1])
            l >>= 1
            r >>= 1
        return res
import sys, random
input = sys.stdin.buffer.readline
n = int(input())
p = list(map(lambda x: int(x) - 1, input().split()))
a = list(map(float, input().split()))
pos = [0 for i in range(n + 1)]
for i in range(n):
    pos[p[i]] = i
data = [0] * n
S = 0
for i in range(n):
    S += a[pos[i]]
    data[i] = S
init = [0] * n
for i in range(0, n):
    if p[i] > 0:
        init[i] += a[i]
    else:
        init[i] -= a[i]
    init[i] += init[i - 1]
LST = LazySegmentTree(n, init)
ans = a[0]
for i in range(n):
    tmp = data[i] + LST.query(0, n - 1)
    ans = min(ans, tmp)
    LST.update(pos[i + 1], n, -2 * a[pos[i + 1]])
print(int(ans))

Solution (Python):
import sys
readline = sys.stdin.readline
from itertools import accumulate

class Lazysegtree:

    def __init__(self, A, intv, initialize=True, segf=min):
        self.N = len(A)
        self.N0 = 2 ** (self.N - 1).bit_length()
        self.intv = intv
        self.segf = segf
        self.lazy = [0] * (2 * self.N0)
        if initialize:
            self.data = [intv] * self.N0 + A + [intv] * (self.N0 - self.N)
            for i in range(self.N0 - 1, 0, -1):
                self.data[i] = self.segf(self.data[2 * i], self.data[2 * i + 1])
        else:
            self.data = [intv] * (2 * self.N0)

    def _ascend(self, k):
        k = k >> 1
        c = k.bit_length()
        for j in range(c):
            idx = k >> j
            self.data[idx] = self.segf(self.data[2 * idx], self.data[2 * idx + 1]) + self.lazy[idx]

    def _descend(self, k):
        k = k >> 1
        idx = 1
        c = k.bit_length()
        for j in range(1, c + 1):
            idx = k >> c - j
            ax = self.lazy[idx]
            if not ax:
                continue
            self.lazy[idx] = 0
            self.data[2 * idx] += ax
            self.data[2 * idx + 1] += ax
            self.lazy[2 * idx] += ax
            self.lazy[2 * idx + 1] += ax

    def query(self, l, r):
        L = l + self.N0
        R = r + self.N0
        Li = L // (L & -L)
        Ri = R // (R & -R)
        self._descend(Li)
        self._descend(Ri - 1)
        s = self.intv
        while L < R:
            if R & 1:
                R -= 1
                s = self.segf(s, self.data[R])
            if L & 1:
                s = self.segf(s, self.data[L])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def add(self, l, r, x):
        L = l + self.N0
        R = r + self.N0
        Li = L // (L & -L)
        Ri = R // (R & -R)
        while L < R:
            if R & 1:
                R -= 1
                self.data[R] += x
                self.lazy[R] += x
            if L & 1:
                self.data[L] += x
                self.lazy[L] += x
                L += 1
            L >>= 1
            R >>= 1
        self._ascend(Li)
        self._ascend(Ri - 1)

    def binsearch(self, l, r, check, reverse=False):
        L = l + self.N0
        R = r + self.N0
        Li = L // (L & -L)
        Ri = R // (R & -R)
        self._descend(Li)
        self._descend(Ri - 1)
        (SL, SR) = ([], [])
        while L < R:
            if R & 1:
                R -= 1
                SR.append(R)
            if L & 1:
                SL.append(L)
                L += 1
            L >>= 1
            R >>= 1
        if reverse:
            for idx in SR + SL[::-1]:
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                ax = self.lazy[idx]
                self.lazy[idx] = 0
                self.data[2 * idx] += ax
                self.data[2 * idx + 1] += ax
                self.lazy[2 * idx] += ax
                self.lazy[2 * idx + 1] += ax
                idx = idx << 1
                if check(self.data[idx + 1]):
                    idx += 1
            return idx - self.N0
        else:
            for idx in SL + SR[::-1]:
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                ax = self.lazy[idx]
                self.lazy[idx] = 0
                self.data[2 * idx] += ax
                self.data[2 * idx + 1] += ax
                self.lazy[2 * idx] += ax
                self.lazy[2 * idx + 1] += ax
                idx = idx << 1
                if not check(self.data[idx]):
                    idx += 1
            return idx - self.N0
N = int(readline())
P = list(map(lambda x: int(x) - 1, readline().split()))
Pinv = [None] * N
for i in range(N):
    Pinv[P[i]] = i
A = list(map(int, readline().split()))
dp = A[:-1]
for i in range(1, N - 1):
    dp[i] += dp[i - 1]
inf = 1 << 60
ans = dp[0]
dp = Lazysegtree(dp, inf, initialize=True, segf=min)
N0 = dp.N0
cnt = 0
for i in range(N):
    a = A[Pinv[i]]
    p = Pinv[i]
    dp.add(p, N0, -2 * a)
    cnt += a
    ans = min(ans, cnt + dp.query(0, N0))
print(ans)