Army Creation (Codeforces 813E)
Tags: Others, binary search

As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires.In the game Vova can hire n different warriors; ith warrior has the type ai. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if for each type of warrior present in the game there are not more than k warriors of this type in the army. Of course, Vova wants his army to be as large as possible.To make things more complicated, Vova has to consider q different plans of creating his army. ith plan allows him to hire only warriors whose numbers are not less than li and not greater than ri.Help Vova to determine the largest size of a balanced army for each plan.Be aware that the plans are given in a modified way. See input section for details.

Input: The first line contains two integers n and k (1 ≤ n, k ≤ 100000).The second line contains n integers a1, a2, ... an (1 ≤ ai ≤ 100000).The third line contains one integer q (1 ≤ q ≤ 100000).Then q lines follow. ith line contains two numbers xi and yi which represent ith plan (1 ≤ xi, yi ≤ n).You have to keep track of the answer to the last plan (let's call it last). In the beginning last = 0. Then to restore values of li and ri for the ith plan, you have to do the following:  li = ((xi + last) mod n) + 1;  ri = ((yi + last) mod n) + 1;  If li > ri, swap li and ri. 

Output: Print q numbers. ith number must be equal to the maximum size of a balanced army when considering ith plan.

Note: In the first example the real plans are:   1 2  1 6  6 6  2 4  4 6 

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

Sample Outputs:
2
4
1
3
2

Solution (Python):
import bisect
import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
m = pow(10, 5) + 5
x = [[] for _ in range(m)]
for i in range(n):
    x[a[i]].append(i)
b = [0] * n
for i in range(m):
    xi = x[i]
    for j in range(k, len(xi)):
        b[xi[j]] = xi[j - k] + 1
z = [[] for _ in range(200)]
for i in range(n):
    z[i // 500].append(b[i])
for i in range(200):
    z[i].sort()
q = int(input())
last = 0
ans = []
for _ in range(q):
    (x, y) = map(int, input().split())
    l = (x + last) % n
    r = (y + last) % n
    if l > r:
        (l, r) = (r, l)
    l0 = l
    ans0 = 0
    while l % 500 and l <= r:
        if b[l] <= l0:
            ans0 += 1
        l += 1
    while not r % 500 == 499 and l <= r:
        if b[r] <= l0:
            ans0 += 1
        r -= 1
    while l < r:
        ans0 += bisect.bisect_left(z[l // 500], l0 + 0.5)
        l += 500
    ans.append(ans0)
    last = ans0
print('\n'.join(map(str, ans)))

Solution (Python):
class segtree:

    def __init__(self, init, func, ide):
        self.n = len(init)
        self.func = func
        self.ide = ide
        self.size = 1 << (self.n - 1).bit_length()
        self.tree = [self.ide for i in range(2 * self.size)]
        for i in range(self.n):
            self.tree[self.size + i] = init[i]
        for i in range(self.size - 1, 0, -1):
            self.tree[i] = self.func(self.tree[2 * i], self.tree[2 * i | 1])

    def update(self, k, x):
        k += self.size
        self.tree[k] = x
        k >>= 1
        while k:
            self.tree[k] = self.func(self.tree[2 * k], self.tree[k * 2 | 1])
            k >>= 1

    def get(self, i):
        return self.tree[i + self.size]

    def query(self, l, r):
        L = l
        l += self.size
        r += self.size
        ans = 0
        while l < r:
            if l & 1:
                ans += count(self.tree[l], L)
                l += 1
            if r & 1:
                r -= 1
                ans += count(self.tree[r], L)
            l >>= 1
            r >>= 1
        return ans

    def debug(self, s=10):
        print([self.get(i) for i in range(min(self.n, s))])

def op(x, y):
    return sorted(x + y)
import bisect

def count(arr, x):
    return bisect.bisect_left(arr, x)
from sys import stdin
input = lambda : stdin.readline()[:-1]
(n, k) = map(int, input().split())
a = list(map(lambda x: int(x) - 1, input().split()))
idx = [[] for i in range(10 ** 5)]
b = [0] * n
for i in range(n):
    if len(idx[a[i]]) < k:
        b[i] = -1
    else:
        b[i] = idx[a[i]][-k]
    idx[a[i]].append(i)
seg = segtree([[i] for i in b], op, [])
lst = 0
q = int(input())
for _ in range(q):
    (x, y) = map(int, input().split())
    l = (x + lst) % n
    r = (y + lst) % n
    if l > r:
        (l, r) = (r, l)
    ans = seg.query(l, r + 1)
    print(ans)
    lst = ans

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        inf = float('inf')

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import math
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

class SegTree:

    def __init__(self, e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None:
        self._e = e
        if isinstance(v, int):
            v = [e] * v
        self._n = len(v)
        self._log = (self._n - 1).bit_length()
        self._size = 1 << self._log
        self._d = [e] * (2 * self._size)
        for i in range(self._n):
            self._d[self._size + i] = v[i]
        for i in range(self._size - 1, 0, -1):
            self._d[i] = list(merge(self._d[2 * i], self._d[2 * i + 1]))

    def prod(self, left: int, right: int, x: int) -> typing.Any:
        assert 0 <= left <= right <= self._n
        ans = 0
        left += self._size
        right += self._size
        while left < right:
            if left & 1:
                ans += bisect.bisect_left(self._d[left], x)
                left += 1
            if right & 1:
                right -= 1
                ans += bisect.bisect_left(self._d[right], x)
            left >>= 1
            right >>= 1
        return ans

def main():
    (n, k) = MII()
    col = LGMI()
    tmp = [[] for _ in range(100000)]
    last_pos = [-1] * n
    for i in range(n):
        if len(tmp[col[i]]) >= k:
            last_pos[i] = tmp[col[i]][-k]
        tmp[col[i]].append(i)
    del tmp
    seg = SegTree([], [[i] for i in last_pos])
    ans = 0
    q = II()
    for _ in range(q):
        (l, r) = MII()
        (ql, qr) = ((l + ans) % n, (r + ans) % n)
        if ql > qr:
            (ql, qr) = (qr, ql)
        ans = seg.prod(ql, qr + 1, ql)
        print(ans)
    return
t = 1
for _ in range(t):
    main()