Exotic Queries (Codeforces 1864F)
Tags: Implement, sortings

AquaMoon gives RiverHamster a sequence of integers $$$a_1,a_2,\dots,a_n$$$, and RiverHamster gives you $$$q$$$ queries. Each query is expressed by two integers $$$l$$$ and $$$r$$$. For each query independently, you can take any continuous segment of the sequence and subtract an identical non-negative value from all the numbers of this segment. You can do so multiple (possibly, zero) times. However, you may not choose two intersecting segments which are not included in one another. Your goal is to convert to $$$0$$$ all numbers whose initial value was within the range $$$[l, r]$$$. You must do so in the minimum number of operations.Please note that the queries are independent, the numbers in the array are restored to their initial values between the queries.Formally, for each query, you are to find the smallest $$$m$$$ such that there exists a sequence $$$\{(x_j,y_j,z_j)\}_{j=1}^{m}$$$ satisfying the following conditions:  for any $$$1 \le j \leq m$$$, $$$z_j \ge 0$$$ and $$$1 \le x_j \le y_j \leq n$$$ (here $$$[x_j, y_j]$$$ correspond to the segment of the sequence);  for any $$$1 \le j < k \le m$$$, it is true that $$$[x_j,y_j]\subseteq[x_{k},y_{k}]$$$, or $$$[x_k,y_k]\subseteq[x_{j},y_{j}]$$$, or $$$[x_j,y_j]\cap[x_{k},y_{k}]=\varnothing$$$;  for any $$$1 \le i \le n$$$, such that $$$l \le a_i \leq r$$$, it is true that $$$$$${\large a_i = \sum\limits_{\substack {1 \le j \le m \\ x_j \le i \le y_j}} z_j. }$$$$$$ 

Input: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\le n,q\le 10^6$$$).The second line contains $$$n$$$ integers integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$).Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1\le l\le r\le n$$$), representing a query.

Output: For each query, output the answer for this query on a separate line.

Note: In the first test case, consider the second query, when $$$l = 2$$$, $$$r = 2$$$. The elements to be manipulated are $$$[a_3, a_5, a_{10}] = [2, 2, 2]$$$. It is sufficient to apply the operation sequence $$$\{(2, 10, 2)\}$$$.Consider the fourth query, when $$$l = 2$$$, $$$r = 3$$$. The elements to be manipulated are $$$[a_3, a_4, a_5, a_7, a_{10}] = [2, 3, 2, 3, 2]$$$. It is sufficient to apply the operation sequence $$$\{(1, 10, 2), (4, 4, 1), (7, 7, 1)\}$$$.In the second test case, note that the operation sequence $$$\{(1, 2, 1), (2, 3, 2)\}$$$ is invalid because the two segments intersect but neither is contained inside the other.

Sample Inputs:
10 8
1 6 2 3 2 6 3 10 1 2
1 10
2 2
3 3
2 3
1 3
3 6
4 6
5 5

3 1
1 3 2
1 3

Sample Outputs:
8
1
1
3
5
3
1
0

3

Solution (Python):
import io, os
import sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

class fenwick(object):

    def __init__(self, n):
        self.n = n
        self.cul = [0] * n
        self.maxd = len(bin(n)) - 3

    def update(self, index, diff):
        i = index
        while i < self.n:
            self.cul[i] += diff
            i += i + 1 & -i - 1

    def getaccu(self, index):
        output = 0
        i = index
        while i >= 0:
            output += self.cul[i]
            i -= i + 1 & -i - 1
        return output

class segment_tree(object):

    def merge(self, num, accu):
        if self.flag:
            return min(accu, num)
        else:
            return max(accu, num)

    def __init__(self, n, flag):
        self.n = n
        self.flag = flag
        if self.flag:
            self.inf = float('inf')
        else:
            self.inf = 0
        self.arr = [self.inf] * (2 * n)

    def update(self, index, target):
        index += self.n
        self.arr[index] = target
        while index > 0:
            if index & 1:
                nexttarget = self.merge(self.arr[index], self.arr[index - 1])
            else:
                nexttarget = self.merge(self.arr[index], self.arr[index + 1])
            self.arr[index >> 1] = nexttarget
            index = index >> 1

    def addnum(self, index, diff):
        self.update(index, self.arr[index + self.n] + diff)

    def query(self, left, right):
        (i, j) = (self.n + left, self.n + right + 1)
        output = self.inf
        while i < j:
            if i & 1:
                output = self.merge(self.arr[i], output)
                i += 1
            if j & 1:
                j -= 1
                output = self.merge(self.arr[j], output)
            i = i >> 1
            j = j >> 1
        return output

def main(t):
    (n, q) = map(int, input().split())
    arr = list(map(int, input().split()))
    indexes = [[] for _ in range(n + 1)]
    data = [[] for _ in range(n + 1)]
    for i in range(n):
        indexes[arr[i]].append(i)
    seg = segment_tree(n, False)
    for num in range(1, n + 1):
        if len(indexes[num]) == 0:
            continue
        sub = indexes[num]
        seg.update(sub[0], num)
        data[num].append(num)
        for i in range(1, len(sub)):
            maximum = seg.query(sub[i - 1] + 1, sub[i] - 1)
            if maximum > 0:
                data[maximum].append(num)
            seg.update(sub[i], num)
    query = [[] for _ in range(n + 1)]
    for i in range(q):
        (l, r) = map(int, input().split())
        query[l].append((r, i))
    ans = [0] * q
    fen = fenwick(n + 1)
    p = 0
    for l in range(n, 0, -1):
        for a in data[l]:
            fen.update(a, 1)
        for (r, i) in query[l]:
            ans[i] = fen.getaccu(r) - fen.getaccu(l - 1)
    for num in ans:
        sys.stdout.write(str(num) + '\n')
T = 1
t = 1
while t <= T:
    main(t)
    t += 1

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f(u, v):
    return u * (n + 1) + v

def update(i, x):
    i += l1
    tree[i] = x
    i >>= 1
    while i:
        tree[i] = max(tree[2 * i], tree[2 * i + 1])
        i >>= 1
    return

def get_max(s, t):
    (s, t) = (s + l1, t + l1)
    ans = 0
    while s <= t:
        if s & 1:
            ans = max(ans, tree[s])
            s += 1
        s >>= 1
        if not t & 1:
            ans = max(ans, tree[t])
            t -= 1
        t >>= 1
    return ans

def make_graph(n, m):
    (x, s) = ([0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        j = i >> 1
        s[l0[j] + 2] += 1
        (x[i], x[i + 1]) = (l0[j], j)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    G = [0] * m
    for i in range(0, 2 * m, 2):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        s[j] += 1
    return (G, s)

def get_sum0(i):
    s = 0
    while i > 0:
        s += tree[i]
        i -= i & -i
    return s

def get_sum(s, t):
    ans = 0 if s > t else get_sum0(t) - get_sum0(s - 1)
    return ans

def add(i, x):
    while i < len(tree):
        tree[i] += x
        i += i & -i
(n, q) = map(int, input().split())
a = list(map(int, input().split()))
x = [f(a[i], i) for i in range(n)]
x.sort()
l1 = pow(2, (n + 1).bit_length())
l2 = 2 * l1
tree = [0] * l2
tree0 = [0] * (n + 1)
u = []
for i in range(n - 1):
    (l, r) = (x[i] % (n + 1), x[i + 1] % (n + 1))
    if a[l] == a[r]:
        ma = get_max(l, r)
        if ma:
            tree0[a[l]] += 1
            u.append(f(ma, a[l]))
    update(l, a[l])
tree = tree0
for i in range(1, n + 1):
    j = i + (i & -i)
    if j < len(tree):
        tree[j] += tree[i]
(cnt, s) = ([0] * (n + 1), [0] * (n + 1))
for i in a:
    cnt[i] += 1
    s[i] = 1
for i in range(1, n + 1):
    cnt[i] += cnt[i - 1]
    s[i] += s[i - 1]
(l0, r0) = ([0] * q, [0] * q)
for i in range(q):
    (l, r) = map(int, input().split())
    (l0[i], r0[i]) = (l, r)
(G, s0) = make_graph(n, q)
u.sort()
j = 0
ans = [0] * q
for l in range(1, n + 1):
    for v in range(s0[l], s0[l + 1]):
        i = G[v]
        r = r0[i]
        v = s[r] - s[l - 1]
        ans0 = v + get_sum(l, r)
        ans[i] = ans0
    while j < len(u) and u[j] // (n + 1) == l:
        k = u[j] % (n + 1)
        add(k, -1)
        j += 1
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f(u, v):
    return u * (n + 1) + v

def update(i, x):
    i += l1
    tree[i] = x
    i >>= 1
    while i:
        tree[i] = max(tree[2 * i], tree[2 * i + 1])
        i >>= 1
    return

def get_max(s, t):
    (s, t) = (s + l1, t + l1)
    ans = 0
    while s <= t:
        if s & 1:
            ans = max(ans, tree[s])
            s += 1
        s >>= 1
        if not t & 1:
            ans = max(ans, tree[t])
            t -= 1
        t >>= 1
    return ans

def make_graph(n, m):
    (x, s) = ([0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        j = i >> 1
        s[l0[j] + 2] += 1
        (x[i], x[i + 1]) = (l0[j], j)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    G = [0] * m
    for i in range(0, 2 * m, 2):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        s[j] += 1
    return (G, s)

def get_sum0(i):
    s = 0
    while i > 0:
        s += tree[i]
        i -= i & -i
    return s

def get_sum(s, t):
    ans = 0 if s > t else get_sum0(t) - get_sum0(s - 1)
    return ans

def add(i, x):
    while i < len(tree):
        tree[i] += x
        i += i & -i
(n, q) = map(int, input().split())
a = list(map(int, input().split()))
x = [f(a[i], i) for i in range(n)]
x.sort()
l1 = pow(2, (n + 1).bit_length())
l2 = 2 * l1
tree = [0] * l2
tree0 = [0] * (n + 1)
u = []
for i in range(n - 1):
    (l, r) = (x[i] % (n + 1), x[i + 1] % (n + 1))
    if a[l] == a[r]:
        ma = get_max(l, r)
        if ma:
            tree0[a[l]] += 1
            u.append(f(ma, a[l]))
    update(l, a[l])
tree = tree0
for i in range(1, n + 1):
    j = i + (i & -i)
    if j < len(tree):
        tree[j] += tree[i]
(cnt, s) = ([0] * (n + 1), [0] * (n + 1))
for i in a:
    cnt[i] += 1
    s[i] = 1
for i in range(1, n + 1):
    cnt[i] += cnt[i - 1]
    s[i] += s[i - 1]
(l0, r0) = ([0] * q, [0] * q)
for i in range(q):
    (l, r) = map(int, input().split())
    (l0[i], r0[i]) = (l, r)
(G, s0) = make_graph(n, q)
u.sort()
j = 0
ans = [0] * q
for l in range(1, n + 1):
    for v in range(s0[l], s0[l + 1]):
        i = G[v]
        r = r0[i]
        v = s[r] - s[l - 1]
        ans0 = v + get_sum(l, r)
        ans[i] = ans0
    while j < len(u) and u[j] // (n + 1) == l:
        k = u[j] % (n + 1)
        add(k, -1)
        j += 1
sys.stdout.write('\n'.join(map(str, ans)))