Problem:


Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the response to the i-th query.

Sample Input 1

4 3
1 2 1 3
1 3
2 4
3 3

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

10 10
2 5 6 5 2 1 7 9 7 2
5 5
2 4
6 7
2 2
7 8
7 9
1 8
6 9
8 10
6 8

Sample Output 2

1
2
2
1
2
2
6
3
3
3



Sample input:
4 3
1 2 1 3
1 3
2 4
3 3


Sample output:
2
3
1

Submission status: Time Limit Exceeded

Solution code:
import sys
import math

def input(): return sys.stdin.readline().rstrip("\r\n")
def List(): return list(map(int, input().split()))
def Num(): return int(input())


freq = [0] * 1000001
dist = 0


class Query(object):
    def __init__(self, l, r, qr_no, block_no):
        self.l = int(l)
        self.r = int(r)
        self.qr_no = int(qr_no)
        self.block_no = int(block_no)


def add(ele):
    global freq, dist
    if freq[ele] == 0:
        dist += 1
    freq[ele] += 1


def remove(ele):
    global freq, dist
    freq[ele] -= 1
    if freq[ele] == 0:
        dist -= 1


n, q = List()
a = List()
Q = []
ans = [0] * q
root = int(math.sqrt(n))
for i in range(q):
    l, r = List()
    l -= 1
    r -= 1
    Q.append(Query(l, r, i, l // root))
Q.sort(key = lambda i: i.r)
Q.sort(key = lambda i: i.l)
curr_l, curr_r = Q[0].l, Q[0].r
for i in range(Q[0].l, Q[0].r + 1):
    add(a[i])
ans[Q[0].qr_no] = dist
for i in range(1, len(Q)):
    while curr_l < Q[i].l:
        remove(a[curr_l])
        curr_l += 1
    while curr_l > Q[i].l:
        curr_l -= 1
        add(a[curr_l])
    while curr_r < Q[i].r:
        curr_r += 1
        add(a[curr_r])
    while curr_r > Q[i].r:
        remove(a[curr_r])
        curr_r -= 1
    ans[Q[i].qr_no] = dist
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())
from bisect import bisect

def resolve():
    it = map(int, sys.stdin.read().split())
    N, Q = next(it), next(it)
    C = [next(it) for i in range(N)]
    D = list(zip(it, it, range(Q)))

    D.sort(key=lambda x: (x[1], x[0]), reverse=True)

    C1 = [[-1, []] for i in range(N)]
    rx = D[0][1]
    for i, ci in zip(range(rx), C):
        x = C1[ci-1]
        x[1].append(x[0])
        x[0] = i
    C2 = C1[:]
    C2.sort()

    ans = [0] * Q
    rj = rx
    for li, ri, i in D:
        if ri < rj:
            for j in reversed(range(ri, rj)):
                cj = C[j] - 1
                x = C1[cj]
                x[0] = x[1].pop()
            C2.sort()
            rj = ri

        k = bisect(C2, [li-1,])
        ans[i] = N - k

    print(*ans, sep="\n")


if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
read=sys.stdin.buffer.readline

class BIT:
    def __init__(self,N):
        self.N=N
        self.bit=[0]*N
    def add(self,a,w):
        x=a
        while(x<self.N):
            self.bit[x]+=w
            x|=x+1
    def get(self,a):
        ret,x=0,a-1
        while(x>=0):
            ret+=self.bit[x]
            x=(x&(x+1))-1
        return ret
    def cum(self,l,r):
        return self.get(r)-self.get(l)

def main():
    def update(x,i):
        if good[x]==-1:
            good[x]=i
            bit.add(i,1)
        else:
            bit.add(good[x],-1)
            good[x]=i
            bit.add(good[x],1)
        return
    
    N,Q=map(int,read().split())
    c=list(map(int,read().split()))
    li=[list(map(lambda x:int(x)-1,read().split())) for i in range(Q)]
    Query=[(li[i][0],li[i][1],i) for i in range(Q)]
    Query.sort(key=lambda x:x[1])
    ans=[-1]*Q
    good=[-1]*(N+1)
    bit=BIT(N)

    i=0
    for L,R,w in Query:
        while(i<=R):
            update(c[i],i)
            i+=1
        ans[w]=bit.cum(L,R+1)

    print(*ans,sep='\n')
    return
    
if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
read=sys.stdin.buffer.readline

class BIT:
    def __init__(self,N):
        self.N=N
        self.bit=[0]*N
    def add(self,a,w):
        x=a
        while(x<self.N):
            self.bit[x]+=w
            x|=x+1
    def get(self,a):
        ret,x=0,a-1
        while(x>=0):
            ret+=self.bit[x]
            x=(x&(x+1))-1
        return ret
    def cum(self,l,r):
        return self.get(r)-self.get(l)

def main():
    def update(x,i):
        if good[x]==-1:
            good[x]=i
            bit.add(i,1)
        else:
            bit.add(good[x],-1)
            good[x]=i
            bit.add(good[x],1)
        return
    
    N,Q=map(int,read().split())
    c=list(map(int,read().split()))
    li=[list(map(lambda x:int(x)-1,read().split()))+[i] for i in range(Q)]
    Query=[(li[i][0],li[i][1],i) for i in range(Q)]
    Query.sort(key=lambda x:x[1])
    ans=[-1]*Q
    good=[-1]*(N+1)
    bit=BIT(N)

    i=0
    for L,R,w in Query:
        while(i<=R):
            update(c[i],i)
            i+=1
        ans[w]=bit.cum(L,R+1)

    print(*ans,sep='\n')
    return
    
if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
read=sys.stdin.buffer.readline

class BIT:
    def __init__(self,N):
        self.N=N
        self.bit=[0]*N
    def add(self,a,w):
        x=a
        while(x<self.N):
            self.bit[x]+=w
            x|=x+1
    def get(self,a):
        ret,x=0,a-1
        while(x>=0):
            ret+=self.bit[x]
            x=(x&(x+1))-1
        return ret
    def cum(self,l,r):
        return self.get(r)-self.get(l)

def main():
    def update(x,i):
        if good[x]==-1:
            good[x]=i
            bit.add(i,1)
        else:
            bit.add(good[x],-1)
            good[x]=i
            bit.add(good[x],1)
    
    N,Q=map(int,read().split())
    c=list(map(int,read().split()))
    li=[list(map(lambda x:int(x)-1,read().split()))+[i] for i in range(Q)]
    Query=[(li[i][0],li[i][1],i) for i in range(Q)]
    Query.sort(key=lambda x:x[1])
    ans=[-1]*Q
    good=[-1]*(N+1)
    bit=BIT(N)

    i=0
    for L,R,w in Query:
        while(i<=R and i<N):
            update(c[i],i)
            i+=1
        ans[w]=bit.cum(L,R+1)

    print(*ans,sep='\n')
    
if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50


class BIT:
    # init_val[0] -> bins[1]
    def __init__(self, n, init_val, init):
        self.n = n
        self.init_val = init_val
        self.init = init
        self.k = math.ceil(math.log2(n))

        try:
            init_val[0]
        except:
            raise ValueError('init_val should be list')

        self.bins = [self.init] * ((1 << self.k) + 1)
        for i, val in enumerate(self.init_val):
            bi = i + 1
            if bi & 1:
                self.bins[bi] = val
            else:
                ret = self.init
                most_sig = (bi & -bi)
                n_bit = bi - 1
                while n_bit:
                    v = n_bit & -n_bit
                    if most_sig >= v: break
                    ret = self.compare(ret, self.bins[n_bit])
                    n_bit -= v
                self.bins[bi] = ret

    def compare(self, l, r):
        return l + r

    def minus(self, val):
        return -val

    def update(self, idx, by, minus=False):
        '''idx : 0-started index'''
        if minus:
            by = self.minus(by)
        idx += 1
        while idx < len(self.bins):
            self.bins[idx] = self.compare(self.bins[idx], by)
            idx += (idx & -idx)

    def eval(self, idx):
        '''idx: 0-indexed'''
        ans = self.init
        idx += 1
        while idx:
            ans = self.compare(ans, self.bins[idx])
            idx -= (idx & -idx)
        return ans

    def eval_between(self, l, r):
        ''' l, r : 0-indexed '''
        return self.compare(self.eval(r), self.minus(self.eval(l - 1)))

def run():
    N, Q = map(int, sysread().split())
    right_arr = [-1] * (N+1)
    C = list(map(int, sysread().split()))

    L,R = [],[]
    for i in range(Q):
        l,r = map(int, sysread().split())
        L.append((l, i))
        R.append((r, i))
    perms = [i for r,i in sorted(R)]
    ans = [-1] * Q

    bit = BIT(N, init_val = [0]*N, init=0)
    checked = -1
    for perm in perms:
        r, i = R[perm]
        l, _ = L[perm]
        r -= 1
        l -= 1
        #print(l, r)
        for idx, c in enumerate(C[checked+1:r+1], checked+1):
            if right_arr[c] < idx:
                pre_idx = right_arr[c]
                right_arr[c] = idx
                if pre_idx != -1:
                    bit.update(pre_idx, by=1, minus=True)
                bit.update(idx, by=1, minus=False)
                #print(pre_idx, idx, c, seg.bins)
        sub = bit.eval(l-1) if l > 0 else 0
        val = bit.eval(r) - sub
        ans[i] = val
        checked = r
        #print(val)

    for a in ans:
        print(a)




if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
read=sys.stdin.readline

class BIT:
    def __init__(self,N):
        self.N=N
        self.bit=[0]*N
    def add(self,a,w):
        x=a
        while(x<self.N):
            self.bit[x]+=w
            x|=x+1
    def get(self,a):
        ret,x=0,a-1
        while(x>=0):
            ret+=self.bit[x]
            x=(x&(x+1))-1
        return ret
    def cum(self,l,r):
        return self.get(r)-self.get(l)

def update(x,i):
    if good[x]==-1:
        good[x]=i
        bit.add(i,1)
    else:
        bit.add(good[x],-1)
        good[x]=i
        bit.add(good[x],1)

N,Q=map(int,read().split())
c=list(map(int,read().split()))
Query=[list(map(lambda x:int(x)-1,read().split()))+[i] for i in range(Q)]
Query.sort(key=lambda x:x[1])
ans=[-1]*Q
good=[-1]*(N+1)
bit=BIT(N)


i=0
for L,R,w in Query:
    while(i<=R and i<N):
        update(c[i],i)
        i+=1
    ans[w]=bit.cum(L,R+1)

print(*ans,sep='\n')

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())

def resolve():
    it = map(int, sys.stdin.read().split())
    N, Q = next(it), next(it)
    N1 = (2*N+1)//2
    N2 = N1*2
    dp = [None] * N2

    dp[N2-1] = set()
    for i in range(N):
        ci = next(it)
        dp[N1+i] = {ci}
    for i in reversed(range(1, N1)):
        dp[i] = dp[2*i] | dp[2*i+1]

    ans = [0] * Q
    for i in range(Q):
        li, ri = next(it)-1, next(it)-1

        li += N1; ri += N1

        cx = set()
        while li < ri:
            if li & 1:
                cx |= dp[li]
                li += 1
            if ri & 1 == 0:
                cx |= dp[ri]
                ri -= 1
            li >>= 1; ri >>= 1
        if li == ri:
            cx |= dp[li]
        ans[i] = len(cx)

    print(*ans, sep="\n")


if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline


class BIT:
    def __init__(self, n):
        self.size = n
        self.array = [0] * (n + 1)
        self.e = [0] * n

    def sum(self, i):
        s = 0
        tmp = i
        while tmp > 0:
            s += self.array[tmp]
            tmp -= tmp & -tmp
        return s

    def add(self, i, x):
        self.e[i] += x
        tmp = i + 1
        while tmp <= self.size:
            self.array[tmp] += x
            tmp += tmp & -tmp


def main():
    n, q = map(int, input().split())
    *C, = map(lambda x: int(x) - 1, input().split())
    P = [0] * n
    N = [0] * n
    for i in range(n)[::-1]:
        if P[C[i]]:
            N[i] = P[C[i]]
        P[C[i]] = i
    F = [0] * n
    B = BIT(n)
    for i in range(n):
        if F[C[i]] == 0:
            B.add(i, 1)
            F[C[i]] = 1
    XY = sorted([(tuple(map(int, input().split())), j) for j in range(q)])
    a = 0
    lst = [0] * q
    for (x, y), j in XY:
        for i in range(a, x - 1):
            B.add(N[i], 1)
        a = x - 1
        lst[j] = B.sum(y) - B.sum(x - 1)
    print(*lst, sep="\n")


main()

Submission status: Time Limit Exceeded

Solution code:
import math
import collections
 
n, q = map(int, input().split())
c = list(map(int, input().split()))
 
for i in range(q):
    l, r = map(int, input().split())
    print(len(dict.fromkeys(c[l-1:r])))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def LF(): return list(map(float, input().split()))
def LC(): return [c for c in input().split()]
def LLI(n): return [LI() for _ in range(n)]
def NSTR(n): return [input() for _ in range(n)]

def array2d(N, M, initial=0):
    return [[initial]*M for _ in range(N)]

def copy2d(orig, N, M):
    ret = array2d(N, M)
    for i in range(N):
        for j in range(M):
            ret[i][j] = orig[i][j]
    return ret


INF = float("inf")
MOD = 10**9 + 7

class BIT:
    # 1-index
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


def main():
    N, Q = MAP()
    c = [None]+LI()
    lri = [(l, r, i) for i, (l, r) in enumerate(LLI(Q))]
    ans = [0]*Q

    # クエリは右端でソート
    lri.sort(key=lambda x: x[1])
    good_ball = [-1]*(N+1)
    acc = BIT(N)

    # 1-indexで統一したい
    curr = 1
    # 始めの一つの更新
    acc.add(curr, 1)
    good_ball[c[1]] = 1
    for l, r, i in lri:
        # currがrに到達するまで、良い玉の集合を更新する。
        while r > curr:
            curr += 1
            cc = c[curr]
            # 良い玉が既にあれば、bitから除く
            if good_ball[cc] != -1:
                acc.add(good_ball[cc], -1)
            acc.add(curr, 1)
            # 良い玉の位置を更新する
            good_ball[cc] = curr
        # print(l, r, curr, dict(good_ball))
        # print([acc.sum(i+1) for i in range(N)])

        # クエリに答える
        # [l, r]に対する答えはsum(r)-sum(l-1)
        ans[i] = acc.sum(r)-acc.sum(l-1)

    print(*ans, sep="\n")

    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
from bisect import bisect_left
from itertools import product
from collections import defaultdict
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def LF(): return list(map(float, input().split()))
def LC(): return [c for c in input().split()]
def LLI(n): return [LI() for _ in range(n)]
def NSTR(n): return [input() for _ in range(n)]

def array2d(N, M, initial=0):
    return [[initial]*M for _ in range(N)]

def copy2d(orig, N, M):
    ret = array2d(N, M)
    for i in range(N):
        for j in range(M):
            ret[i][j] = orig[i][j]
    return ret


INF = float("inf")
MOD = 10**9 + 7

class BIT:
    # 1-index
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


def main():
    N, Q = MAP()
    c = [None]+LI()
    lri = [(l, r, i) for i, (l, r) in enumerate(LLI(Q))]
    ans = [0]*Q

    # クエリは右端でソート
    lri.sort(key=lambda x: x[1])
    good_ball = defaultdict(lambda: -1)
    acc = BIT(N)

    # 1-indexで統一したい
    curr = 1
    # 始めの一つの更新
    acc.add(curr, 1)
    good_ball[c[1]] = 1
    for l, r, i in lri:
        # currがrに到達するまで、良い玉の集合を更新する。
        while r > curr:
            curr += 1
            # 良い玉が既にあれば、bitから除く
            if good_ball[c[curr]] != -1:
                acc.add(good_ball[c[curr]], -1)
            acc.add(curr, 1)
            # 良い玉の位置を更新する
            good_ball[c[curr]] = curr
        # print(l, r, curr, dict(good_ball))
        # print([acc.sum(i+1) for i in range(N)])

        # クエリに答える
        # [l, r]に対する答えはsum(r)-sum(l-1)
        ans[i] = acc.sum(r)-acc.sum(l-1)

    print(*ans, sep="\n")

    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50

class segtree:
    def __init__(self, n, init_val=None, init=0):
        self.n = n
        self.init_val = init_val
        self.init = init
        self.k = math.ceil(math.log2(n))

        try:
            init_val[0]
        except:
            raise ValueError('init_val should be list')

        self.bins = [self.init] * (1 << (self.k + 1))
        for idx, i in enumerate(range(1 << self.k, 1 << (self.k + 1))):
            if len(self.init_val) > idx:
                self.bins[i] = init_val[idx]
            else:continue

        self.caliculate()

    def compare(self, l, r):
        return l + r

    def caliculate(self):
        k = self.k
        while k:
            for i in range(1<<k, 1<<(k+1)):
                if not i%2:
                    self.bins[i//2] = self.compare(self.bins[i], self.bins[i+1])
                else:continue
            k -= 1

    def update(self, idx, val):
        '''idx : 0-started index'''
        k = (1<<self.k) + idx
        self.bins[k] = val
        while k>1:
            self.bins[k // 2] = self.compare(self.bins[k // 2 * 2], self.bins[k // 2 * 2 + 1])
            k = k//2

    def update_valonly(self, idx, val):
        '''idx : 0-started index'''
        k = (1 << self.k) + idx
        self.bins[k] = val

    def eval(self, l, r):
        ret = self.init
        l = (1 << self.k) + l
        r = (1 << self.k) + r
        #print(l, r)
        while True:
            #print(l, r)
            if r - l == 1:
                ret = self.compare(ret, self.bins[l])
                ret = self.compare(ret, self.bins[r])
                break
            elif l == r:
                ret = self.compare(ret, self.bins[l])
                break
            else:
                done = False
                if l % 2:
                    ret = self.compare(ret, self.bins[l])
                    l += 1
                    done = True
                if not r % 2:
                    ret = self.compare(ret, self.bins[r])
                    r -= 1
                    done = True
                if not done:
                    l = l // 2
                    r = r // 2
        #print(ret)
        return ret

    def value(self, ind):
        return self.bins[(1<<self.k) + ind]

def run():
    N, Q = map(int, sysread().split())
    right_arr = [-1] * (N+1)
    C = list(map(int, sysread().split()))

    L,R = [],[]
    for i in range(Q):
        l,r = map(int, sysread().split())
        L.append((l, i))
        R.append((r, i))
    perms = [i for r,i in sorted(R)]
    ans = [-1] * Q

    seg = segtree(N, init_val = [0]*N, init=0)
    checked = -1
    for perm in perms:
        r, i = R[perm]
        l, _ = L[perm]
        r -= 1
        l -= 1
        #print(l, r)
        for idx, c in enumerate(C[checked+1:r+1], checked+1):
            if right_arr[c] < idx:
                pre_idx = right_arr[c]
                right_arr[c] = idx
                if pre_idx != -1:
                    seg.update_valonly(pre_idx, 0)
                seg.update_valonly(idx, 1)
                seg.caliculate()
                #print(pre_idx, idx, c, seg.bins)
        sub = seg.eval(0, l-1) if l > 0 else 0
        val = seg.eval(0, r) - sub
        ans[i] = val
        checked = r
        #print(val)

    for a in ans:
        print(a)




if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50

class segtree:
    def __init__(self, n, init_val=None, init=0):
        self.n = n
        self.init_val = init_val
        self.init = init
        self.k = math.ceil(math.log2(n))

        try:
            init_val[0]
        except:
            raise ValueError('init_val should be list')

        self.bins = [self.init] * (1 << (self.k + 1))
        for idx, i in enumerate(range(1 << self.k, 1 << (self.k + 1))):
            if len(self.init_val) > idx:
                self.bins[i] = init_val[idx]
            else:continue

        self.caliculate()

    def compare(self, l, r):
        return l + r

    def caliculate(self):
        k = self.k
        while k:
            for i in range(1<<k, 1<<(k+1)):
                if not i%2:
                    self.bins[i//2] = self.compare(self.bins[i], self.bins[i+1])
                else:continue
            k -= 1

    def update(self, idx, val):
        '''idx : 0-started index'''
        k = (1<<self.k) + idx
        self.bins[k] = val
        while k>1:
            self.bins[k // 2] = self.compare(self.bins[k // 2 * 2], self.bins[k // 2 * 2 + 1])
            k = k//2


    def eval(self, l, r):
        ret = self.init
        l = (1 << self.k) + l
        r = (1 << self.k) + r
        #print(l, r)
        while True:
            #print(l, r)
            if r - l == 1:
                ret = self.compare(ret, self.bins[l])
                ret = self.compare(ret, self.bins[r])
                break
            elif l == r:
                ret = self.compare(ret, self.bins[l])
                break
            else:
                done = False
                if l % 2:
                    ret = self.compare(ret, self.bins[l])
                    l += 1
                    done = True
                if not r % 2:
                    ret = self.compare(ret, self.bins[r])
                    r -= 1
                    done = True
                if not done:
                    l = l // 2
                    r = r // 2
        #print(ret)
        return ret

    def value(self, ind):
        return self.bins[(1<<self.k) + ind]

def run():
    N, Q = map(int, sysread().split())
    right_arr = [-1] * (N+1)
    C = list(map(int, sysread().split()))

    L,R = [],[]
    for i in range(Q):
        l,r = map(int, sysread().split())
        L.append((l, i))
        R.append((r, i))
    perms = [i for r,i in sorted(R)]
    ans = [-1] * Q

    seg = segtree(N, init_val = [0]*N, init=0)
    checked = -1
    for perm in perms:
        r, i = R[perm]
        l, _ = L[perm]
        r -= 1
        l -= 1
        #print(l, r)
        for idx, c in enumerate(C[checked+1:r+1], checked+1):
            if right_arr[c] < idx:
                pre_idx = right_arr[c]
                right_arr[c] = idx
                if pre_idx != -1:
                    seg.update(pre_idx, 0)
                seg.update(idx, 1)
                #print(pre_idx, idx, c, seg.bins)
        sub = seg.eval(0, l-1) if l > 0 else 0
        val = seg.eval(0, r) - sub
        ans[i] = val
        checked = r
        #print(val)

    for a in ans:
        print(a)




if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N, Q = map(int, input().split())
C = list(map(int, input().split()))
LR = []
for i in range(Q):
    l, r = map(int, input().split())
    LR.append((l-1, r-1, i))


class FenwickTree(object):
    def __init__(self, n):
        self._bit = [0] * (n+1)
        self.n = n+1
    
    def add(self, i, a):
        i += 1
        while i < self.n:
            self._bit[i] += a
            i += i & -i
    
    def sum(self, i):
        i += 1
        ret = 0
        while i > 0:
            ret += self._bit[i]
            i -= i & -i
        return ret


def solve():
    memo = [-1] * N
    ST = []
    nst = 0
    for i, c in enumerate(C[::-1]):
        if memo[c-1] >= 0:
            ST.append((N-i-1, memo[c-1]))
            nst += 1
        memo[c-1] = N-i-1
    # ST.sort(reverse=True)
    LR.sort(reverse=True)
    ans =[0 for _ in range(Q)]
    ft = FenwickTree(N+1)
    j = 0
    for l, r, i in LR:
        while j < nst and ST[j][0] >= l:
            ft.add(ST[j][1], 1)
            j += 1
        ans[i] = r - l + 1 - ft.sum(r)
    return ans

if __name__ == "__main__":
    print('\n'.join(map(str, solve())))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N, Q = map(int, input().split())
C = list(map(int, input().split()))
LRST = []
for i in range(Q):
    l, r = map(int, input().split())
    LRST.append((l-1, 0, r-1, i))


class FenwickTree(object):
    def __init__(self, n):
        self._bit = [0] * (n+1)
        self.n = n+1
    
    def add(self, i, a):
        i += 1
        while i < self.n:
            self._bit[i] += a
            i += i & -i
    
    def sum(self, i):
        i += 1
        ret = 0
        while i > 0:
            ret += self._bit[i]
            i -= i & -i
        return ret


def solve():
    memo = [-1] * N
    for i, c in enumerate(C):
        if memo[c-1] >= 0:
            LRST.append((memo[c-1], 1, i, -1))
        memo[c-1] = i
    LRST.sort(reverse=True)
    ans =[0 for _ in range(Q)]
    ft = FenwickTree(N+1)
    for sl, typ, tr, q in LRST:
        if typ == 1:
            ft.add(tr, 1)
        else:
            ans[q] = tr - sl + 1 - ft.sum(tr)
    return ans

if __name__ == "__main__":
    print('\n'.join(map(str, solve())))

Submission status: Time Limit Exceeded

Solution code:
import sys


class BinaryIndexedTree(object):
    '''
    1-indexed
    '''
    def __init__(self, A):
        self.__n = len(A)
        self.__node = [0] * (self.__n + 1)
        self.__data = [0] * (self.__n + 1)

        S = [0] * (self.__n + 1)
        for i in range(self.__n):
            S[i + 1] = S[i] + A[i]

        for i in range(1, self.__n + 1):
            self.__data[i] = A[i - 1]
            self.__node[i] = S[i] - S[i - (i & -i)]

    def add(self, i, v):
        self.__data[i] += v
        while i <= self.__n:
            self.__node[i] += v
            i += i & -i

    def sum(self, i):
        ''' [1, i]の和
        '''
        rst = 0
        while i > 0:
            rst += self.__node[i]
            i -= i & -i
        return rst
    
    def get(self, i, j):
        '''[i, j]の和
        '''
        if i == j:
            return self.__data[i]
        else:
            return self.sum(j) - self.sum(i - 1)


def main():
    N, Q = map(int, input().split())
    C = list(map(int, input().split()))

    P = [[] for _ in range(N)]
    for i, c in enumerate(C):
        P[c - 1].append(i)

    right = [0] * N
    for p in P:
        if len(p):
            right[p.pop()] = 1
    BIT = BinaryIndexedTree(right)

    query = []
    for i in range(Q):
        l, r = map(int, sys.stdin.readline().split())
        query.append((r - 1, l - 1, i))

    query.sort(reverse=True)
    ans = [None] * Q

    cur = N - 1
    for r, l, i in query:
        while r < cur:
            c = C[cur] - 1
            # BIT.update(cur + 1, 0)
            p = P[c]
            if len(p):
                BIT.add(p.pop() + 1, 1)
            cur -= 1
        tmp = BIT.get(l + 1, r + 1)
        ans[i] = tmp

    print(*ans, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


class BinaryIndexedTree(object):
    '''
    1-indexed
    '''
    def __init__(self, A):
        self.__n = len(A)
        self.__node = [0] * (self.__n + 1)
        self.__data = [0] * (self.__n + 1)
        for i in range(1, self.__n + 1):
            self.add(i, A[i - 1])
            self.__data[i] = A[i - 1]

    def add(self, i, v):
        self.__data[i] += v
        while i <= self.__n:
            self.__node[i] += v
            i += i & -i

    def sum(self, i):
        ''' [1, i]の和
        '''
        rst = 0
        while i > 0:
            rst += self.__node[i]
            i -= i & -i
        return rst
    
    def get(self, i, j):
        '''[i, j]の和
        '''
        if i == j:
            return self.__data[i]
        else:
            return self.sum(j) - self.sum(i - 1)


def main():
    N, Q = map(int, input().split())
    C = list(map(int, input().split()))

    P = [[] for _ in range(N)]
    for i, c in enumerate(C):
        P[c - 1].append(i)

    right = [0] * N
    for p in P:
        if len(p):
            right[p.pop()] = 1
    BIT = BinaryIndexedTree(right)

    query = []
    for i in range(Q):
        l, r = map(int, sys.stdin.readline().split())
        query.append((r - 1, l - 1, i))

    query.sort(reverse=True)
    ans = [None] * Q

    cur = N - 1
    for r, l, i in query:
        while r < cur:
            c = C[cur] - 1
            # BIT.update(cur + 1, 0)
            p = P[c]
            if len(p):
                BIT.add(p.pop() + 1, 1)
            cur -= 1
        tmp = BIT.get(l + 1, r + 1)
        ans[i] = tmp

    print(*ans, sep='\n')


if __name__ == '__main__':
    main()