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
from operator import itemgetter
buf = sys.stdin.buffer
input = buf.readline
class BIT:
    def __init__(self, n):
        self.n = n
        self.tree = [0] * (n + 1)
    def add(self, i, x):
        n, tree = self.n, self.tree
        while i <= n:
            tree[i] += x
            i += i & -i
    def sum(self, i):
        tree = self.tree
        s = 0
        while i:
            s += tree[i]
            i -= i & -i
        return s
def main():
    n, q = map(int, input().split())
    res = [0] * q
    *c, = map(int, input().split())
    q = [(i, l, r) for i, (l, r) in enumerate(zip(*[map(int, buf.read().split())] * 2))]
    q.sort(key=itemgetter(2))
    bit = BIT(n + 2)
    add, sum = bit.add, bit.sum
    b = [1] * (n + 1)
    j = 1
    for i, l, r in q:
        while j <= r:
            d = c[j - 1]
            j += 1
            k = b[d]
            b[d] = j
            add(k + 1, 1)
            add(j + 1, -1)
        res[i] = sum(l + 1)
    print(' '.join(map(str, res)))
main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys 
from collections import defaultdict
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = 5*10**5+5
data = [0]*(N+1)
###BIT
#akにxを加える
def BIT_add(k,x):
    while k <= N:
        data[k] += x    
        k += k & (-k)
#a1-akの合計を出す
def BIT_sum(k):
    s = 0
    while k:
        s += data[k]
        k -= k & (-k)
    return s

# 入力
NUM, Q = map(int, readline().split())
C = list(map(int,readline().split()))
lr = []
QQ = []
for i in range(Q):
    l,r = map(int,readline().split())
    QQ.append((l,r))
    lr.append((l,r,1))

#前処理 追加用stと合計用lr
d = defaultdict(int)
st = []
for i in range(NUM):
    if d[C[i]] != 0:
        st.append((d[C[i]],i+1,0))
    d[C[i]] = i+1
# stとlrを混ぜてソート
Query = st + lr
Query = sorted(Query,key=lambda x:(-x[0],x[2]))

# クエリの実行
# 0:追加 1:r以下の合計算出
len_q = len(Query)
ans_d = defaultdict(int)
for i in range(len_q):
    x,y,T = Query[i]
    if T == 0:
        BIT_add(y,1)
    else:
        ans_d[(x,y)] = BIT_sum(y)

#出力
for x,y in QQ:
    l = y-x+1
    print(l-ans_d[(x,y)])

Submission status: Time Limit Exceeded

Solution code:
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(set(c[l-1:r])))

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(collections.Counter(c[l-1:r])))

Submission status: Time Limit Exceeded

Solution code:
# cattuper's solution
import sys
input = sys.stdin.buffer.readline
n, q = map(int, input().split())
c = list(map(int, input().split()))
l = [0] * q
r = [0] * q

queries = [[] for _ in range(n)]
rights = [[] for _ in range(n)]
for i in range(q):
    l[i], r[i] = map(int, input().split())
    l[i] -= 1
    queries[l[i]].append(i)

last_app = [-1] * (n+1)
for i in range(n):
    if last_app[c[i]] != -1:
        last = last_app[c[i]]
        rights[last].append(i)
    last_app[c[i]] = i



ans = [0] * q

seg = [0] * (1 << 20)

def add(x):
    x += 1 << 19
    while x:
        seg[x] += 1
        x = x // 2

def sum_of(l, r):
    l += 1 << 19
    r += 1 << 19
    ans = 0
    while l < r:
        if l % 2 == 1:
            ans += seg[l]
            l += 1
        if r % 2 == 1:
            ans += seg[r-1]
            r -= 1
        l //= 2
        r //= 2
    return ans

        
for i in range(n-1, -1, -1):
    for right in rights[i]:
        add(right)
    for q_ind in queries[i]:
        left = l[q_ind]
        right = r[q_ind]
        ans[q_ind] = (right - left) - sum_of(left, right)

for i in range(q):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


class BIT:
    def __init__(self, n):
        self.num = n
        self.dat = [0] * (self.num + 1)
        self.depth = n.bit_length()

    def add(self, i, x):
        i += 1
        while i <= self.num:
            self.dat[i] += x
            i += i & -i

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


n, q = LI()
ans = [0] * q
C = LI()
Q = [[] for _ in range(n)]
for i in range(q):
    l, r = LI()
    Q[l - 1] += [[0, i]]
    Q[r - 1] += [[1, i]]


last = [-1] * (n + 1)
DD = {}
bit = BIT(n + 1)
now = 0
for i, c in enumerate(C):
    col = C[i]
    bit.add(i, 1)
    if last[col] != -1:
        bit.add(last[col], -1)
    last[col] = i
    for flg, qi in Q[i]:
        if flg:
            ans[qi] = bit.sum(i) - bit.sum(DD[qi] - 1)
        else:
            DD[qi] = i
        now += 1


#    print(q_now, "b")

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

Submission status: Time Limit Exceeded

Solution code:
import math
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(set(c[l-1:r])))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,Q=map(int, input().split())

#重複分を引く

class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)
        self.el = [0]*(n+1)
        
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    # I: idx(base: 1), x: value
    def add(self, i, x):
        # assert i > 0
        self.el[i] += x
        while i <= self.n:
            self.data[i] += x
            i += i & -i
            
    # i<x<=j 
    def get(self, i, j=None):
        if j is None:
            return self.el[i]
        return self.sum(j) - self.sum(i)

query=[]

C=list(map(int, input().split()))
for i in range(Q):
    l, r=map(int, input().split())
    query.append((l,r,i))
query=sorted(query, key=lambda x: -x[1])

state=[-1]*N
seg=BIT(N+1)
ans=[0]*Q

for i in range(N):
    while query and query[-1][1]<i+1:
        l,r,j=query.pop()
        ans[j]=r-l+1-(seg.get(l-1,r))

    c=C[i]
    if state[c-1]==-1:
        state[c-1]=i+1
    else:
        idx=state[c-1]
        seg.add(idx,1)
        state[c-1]=i+1
    while query and query[-1][1]==i:
        lq,rq,j=query.pop()
        ans[j]=rq-lq+1-(seg.get(lq-1,rq))
        #print(lq, rq, seg.get(lq-1,rq))



while query:
    lq,rq,j=query.pop()   
    ans[j]=rq-lq+1-(seg.get(lq-1,rq))
    #print(lq, rq, seg.query(lq,rq+1))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


class BIT:
    def __init__(self, n):
        self.num = n
        self.dat = [0] * (self.num + 1)
        self.depth = n.bit_length()

    def add(self, i, x):
        i += 1
        while i <= self.num:
            self.dat[i] += x
            i += i & -i

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


n, q = LI()
ans = [0] * q
C = tuple(map(int, input().split()))
Q = []
for i in range(q):
    l, r = LI()
    Q += [(l-1, 0, i)]
    Q += [(r-1, 1, i)]

Q.sort()
Q += [(INF, 0, 0)]
last = [-1] * (n + 1)
DD = {}
bit = BIT(n + 1)
now = 0
for i, c in enumerate(C):
    col = C[i]
    bit.add(i, 1)
    if last[col] != -1:
        bit.add(last[col], -1)
    last[col] = i
    while Q[now][0] == i:
        idx, flg, qq = Q[now]
        if flg:
            ans[qq] = bit.sum(idx) - bit.sum(DD[qq] - 1)
        else:
            DD[qq] = idx
        now += 1


#    print(q_now, "b")

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


class BIT:
    def __init__(self, n):
        self.num = n
        self.dat = [0] * (self.num + 1)
        self.depth = n.bit_length()

    def add(self, i, x):
        i += 1
        while i <= self.num:
            self.dat[i] += x
            i += i & -i

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


n, q = LI()
ans = [0] * q
C = LI()
Q = []
for i in range(q):
    l, r = LI()
    Q += [(l-1, 0, i)]
    Q += [(r-1, 1, i)]

Q.sort()
Q += [(INF, 0, 0)]
last = [-1] * (n + 1)
DD = {}
bit = BIT(n + 1)
now = 0
for i in range(n):
    col = C[i]
    bit.add(i, 1)
    if last[col] != -1:
        bit.add(last[col], -1)
    last[col] = i
    while Q[now][0] == i:
        idx, flg, qq = Q[now]
        if flg:
            ans[qq] = bit.sum(idx) - bit.sum(DD[qq] - 1)
        else:
            DD[qq] = idx
        now += 1


#    print(q_now, "b")

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


class BIT:
    def __init__(self, size):
        self.bit = [0] * size
        self.size = size
        self.total = 0

    def add(self, i, w):
        x = i + 1
        self.total += w
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        res = 0
        x = i + 1
        while x:
            res += self.bit[x - 1]
            x -= x & -x
        return res


n, q = LI()
ans = [0] * q
C = LI()
Q = []
for i in range(q):
    l, r = LI()
    Q += [(l-1, 0, i)]
    Q += [(r-1, 1, i)]

Q.sort()
Q += [(INF, 0, 0)]
last = [-1] * (n + 1)
DD = {}
bit = BIT(n + 1)
now = 0
for i in range(n):
    col = C[i]
    bit.add(i, 1)
    if last[col] != -1:
        bit.add(last[col], -1)
    last[col] = i
    while Q[now][0] == i:
        idx, flg, qq = Q[now]
        if flg:
            ans[qq] = bit.sum(idx) - bit.sum(DD[qq] - 1)
        else:
            DD[qq] = idx
        now += 1


#    print(q_now, "b")

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


class BIT:
    def __init__(self, size):
        self.bit = [0] * size
        self.size = size
        self.total = 0

    def add(self, i, w):
        x = i + 1
        self.total += w
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        res = 0
        x = i + 1
        while x:
            res += self.bit[x - 1]
            x -= x & -x
        return res


n, q = LI()
ans = [0] * q
C = LI()
Q = []
for i in range(q):
    l, r = LI()
    Q += [(l-1, 0, i)]
    Q += [(r-1, 1, i)]

Q.sort()
Q += [(INF, 0, 0)]
last = [-1] * (n + 1)
DD = {}
bit = BIT(n + 1)
now = 0
for i in range(n):
    col = C[i]
    bit.add(i, 1)
    if last[col] != -1:
        bit.add(last[col], -1)
    last[col] = i
    while Q[now][0] == i:
        idx, flg, qq = Q[now]
        if flg:
            ans[qq] = bit.sum(idx) - bit.sum(DD[qq] - 1)
        else:
            DD[qq] = idx
        now += 1


#    print(q_now, "b")

print('\n'.join(map(str,ans)))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


class BIT:
    def __init__(self, size):
        self.bit = [0] * size
        self.size = size
        self.total = 0

    def add(self, i, w):
        x = i + 1
        self.total += w
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        res = 0
        x = i + 1
        while x:
            res += self.bit[x - 1]
            x -= x & -x
        return res


n, q = LI()
ans = [0] * q
C = LI()
Q = []
for i in range(q):
    l, r = LI()
    Q += [(l-1, 0, i)]
    Q += [(r-1, 1, i)]

Q.sort()
Q += [(INF, 0, 0)]
D = defaultdict(lambda:-1)
DD = {}
bit = BIT(n + 1)
now = 0
for i in range(n):
    col = C[i]
    bit.add(i, 1)
    if D[col] != -1:
        bit.add(D[col], -1)
# print(bisect_right(l_idx, last_idx), "a")
    while Q[now][0] == i:
        idx, flg, qq = Q[now]
        if flg:
            ans[qq] = bit.sum(idx) - bit.sum(DD[qq] - 1)
        else:
            DD[qq] = idx
        now += 1
    D[col] = i

#    print(q_now, "b")


print('\n'.join(map(str,ans)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,Q=map(int, input().split())

#重複分を引く

class SegmentTree:
    def __init__(self, init_value: list, segfunc, ide_ele):
        n = len(init_value)
        self.N0 = 1 << (n - 1).bit_length()
        self.ide_ele = ide_ele
        self.data = [ide_ele] * (2 * self.N0)
        self.segfunc = segfunc
        
        for i, x in enumerate(init_value):
            self.data[i + self.N0 - 1] = x
        for i in range(self.N0 - 2, -1, -1):
            self.data[i] = self.segfunc(self.data[2 * i + 1], self.data[2 * i + 2])
    
    # k: index , x: value
    def update(self, k: int, x):
        k += self.N0 - 1
        ############################
        self.data[k] = x
        ###########################
        while k:
            k = (k - 1) // 2
            self.data[k] = self.segfunc(self.data[k * 2 + 1], self.data[k * 2 + 2])
    
    # rightは開区間  l<=x<r
    def query(self, left: int, right: int):
        L = left + self.N0
        R = right + self.N0
        res = self.ide_ele
        ##########################
        a, b = [], []
        while L < R:
            if L & 1:
                a.append(L - 1)
                L += 1
            if R & 1:
                R -= 1
                b.append(R - 1)
            L >>= 1
            R >>= 1
        for i in a + b[::-1]:
            res = self.segfunc(res, self.data[i])
        ##########################
        return res


C=list(map(int, input().split()))

        
query=[]
for i in range(Q):
    l, r=map(int, input().split())
    query.append((l-1,r-1,i))
query=sorted(query, key=lambda x: -x[1])

A=[0]*(N+1)
def add(a,b):
    return a+b
seg=SegmentTree(A,add,0)
ans=[0]*Q

state=[-1]*N
que=[]
for i in range(N):
    while query and query[-1][1]<i:
        q=query.pop()
        l,r,j=q
        ans[j]=r-l+1-seg.query(l,r+1)
    c=C[i]
    if state[c-1]==-1:
        state[c-1]=i
    else:
        A[state[c-1]]+=1
        seg.update(state[c-1], A[state[c-1]])
        state[c-1]=i
        
    while query and query[-1][1]==i:
        q=query.pop()
        lq,rq,j=q
        
        ans[j]=rq-lq+1-seg.query(lq,rq+1)
        #print(lq, rq, seg.query(lq,rq+1))


while query:
    q=query.pop()
    lq,rq,j=q     
    ans[j]=rq-lq+1-seg.query(lq,rq+1)
    #print(lq, rq, seg.query(lq,rq+1))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
Bsize = 800

def main():
    import sys
    input = sys.stdin.buffer.readline

    N, Q = map(int, input().split())
    A = list(map(int, input().split()))

    query_list = [[] for _ in range(N // Bsize + 1)]
    for q in range(Q):
        l, r = map(int, input().split())
        query_list[(l-1) // Bsize].append((l - 1, r - 1, q))
    for i in range(N // Bsize + 1):
        if query_list[i]:
            if i&1:
                query_list[i].sort(key=lambda x: x[1], reverse=True)
            else:
                query_list[i].sort(key=lambda x: x[1])
    query = []
    for ql in query_list:
        query.extend(ql)

    # [l, r)での求める値を管理するための変数たち
    # 問題によって変える
    cnt = [0] * (N + 1)
    val = 0

    # 区間の伸縮操作
    # 問題によって変える
    def add(i):
        nonlocal val
        if not cnt[A[i]]:
            val += 1
        cnt[A[i]] += 1

    def rem(i):
        nonlocal val
        cnt[A[i]] -= 1
        if not cnt[A[i]]:
            val -= 1

    # init
    l, r, _ = query[0]
    for i in range(l, r + 1):
        add(i)

    # process
    ans = [0] * Q
    for l_new, r_new, q in query:
        if r < r_new:
            for i in range(r + 1, r_new + 1):
                #add(i)
                if not cnt[A[i]]:
                    val += 1
                cnt[A[i]] += 1
        elif r > r_new:
            for i in range(r, r_new, -1):
                #rem(i)
                cnt[A[i]] -= 1
                if not cnt[A[i]]:
                    val -= 1
        if l < l_new:
            for i in range(l, l_new):
                #rem(i)
                cnt[A[i]] -= 1
                if not cnt[A[i]]:
                    val -= 1
        elif l > l_new:
            for i in range(l - 1, l_new - 1, -1):
                #add(i)
                if not cnt[A[i]]:
                    val += 1
                cnt[A[i]] += 1
        l = l_new
        r = r_new
        ans[q] = val

    for a in ans:
        print(a)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,q = map(int,input().split())
c = list(map(int,input().split()))

def popcnt(n):
    c = (n & 0x5555555555555555) + ((n>>1) & 0x5555555555555555)
    c = (c & 0x3333333333333333) + ((c>>2) & 0x3333333333333333)
    c = (c & 0x0f0f0f0f0f0f0f0f) + ((c>>4) & 0x0f0f0f0f0f0f0f0f)
    c = (c & 0x00ff00ff00ff00ff) + ((c>>8) & 0x00ff00ff00ff00ff)
    c = (c & 0x0000ffff0000ffff) + ((c>>16) & 0x0000ffff0000ffff)
    c = (c & 0x00000000ffffffff) + ((c>>32) & 0x00000000ffffffff)
    return c

po = [1]
for i in range(n):
    po.append(po[-1]*2)
li = [0]*n
for i in range(n):
    li[i] = po[c[i] - 1]

def segfunc(x,y):
    return x | y

def init(init_val):
    #set_val
    for i in range(n):
        seg[i+num-1]=init_val[i]
    #built
    for i in range(num-2,-1,-1) :
        seg[i]=segfunc(seg[2*i+1],seg[2*i+2])

def update(k,x):
    k += num-1
    seg[k] = x
    while k:
        k = (k-1)//2
        seg[k] = segfunc(seg[k*2+1],seg[k*2+2])

def query(p,q):
    if q<=p:
        return ide_ele
    p += num-1
    q += num-2
    res=ide_ele
    while q-p>1:
        if p&1 == 0:
            res = segfunc(res,seg[p])
        if q&1 == 1:
            res = segfunc(res,seg[q])
            q -= 1
        p = p//2
        q = (q-1)//2
    if p == q:
        res = segfunc(res,seg[p])
    else:
        res = segfunc(segfunc(res,seg[p]),seg[q])
    return res

#####単位元######
ide_ele = 0

#num:n以上の最小の2のべき乗
num =2**(n-1).bit_length()
seg=[ide_ele]*2*num
init(li)

for _ in range(q):
    l,r = map(int,input().split())
    print(popcnt(query(l-1, r)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,Q=map(int, input().split())

#重複分を引く

class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)
        self.el = [0]*(n+1)
        
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    # I: idx(base: 1), x: value
    def add(self, i, x):
        # assert i > 0
        self.el[i] += x
        while i <= self.n:
            self.data[i] += x
            i += i & -i
            
    # i<=x<j
    def get(self, i, j=None):
        if j is None:
            return self.el[i]
        return self.sum(j) - self.sum(i)


C=list(map(int, input().split()))
state=[-1]*N
que=[]
for i in range(N):
    c=C[i]
    if state[c-1]==-1:
        state[c-1]=i+1
    else:
        que.append((state[c-1],i+1))
        state[c-1]=i+1

que=sorted(que, key=lambda x: x[1])
        
query=[]
for i in range(Q):
    l, r=map(int, input().split())
    query.append((l,r,i))
query=sorted(query, key=lambda x: -x[1])

seg=BIT(N+1)
ans=[0]*Q



for i in range(len(que)):
    while query and query[-1][1]<que[i][1]:
        l,r,j=query.pop()
        ans[j]=r-l+1-(seg.get(l-1,r))

    now=que[i]
    l, r=now  # index
    #A[l]+=1
    seg.add(l, 1)

    while query and query[-1][1]==r:
        lq,rq,j=query.pop()
        
        ans[j]=rq-lq+1-(seg.get(lq-1,rq))
        #print(lq, rq, seg.query(lq,rq+1))
        #print(seg.get(lq,rq+1))

while query:
    lq,rq,j=query.pop()   
    ans[j]=rq-lq+1-(seg.get(lq-1,rq))
    #print(lq, rq, seg.query(lq,rq+1))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,Q=map(int, input().split())

#重複分を引く

class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)
        self.el = [0]*(n+1)
        
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    # I: idx(base: 1), x: value
    def add(self, i, x):
        # assert i > 0
        self.el[i] += x
        while i <= self.n:
            self.data[i] += x
            i += i & -i
            
    # i<=x<j
    def get(self, i, j=None):
        if j is None:
            return self.el[i]
        return self.sum(j) - self.sum(i)


C=list(map(int, input().split()))
state=[-1]*N
que=[]
for i in range(N):
    c=C[i]
    if state[c-1]==-1:
        state[c-1]=i+1
    else:
        que.append((state[c-1],i+1))
        state[c-1]=i+1

que=sorted(que, key=lambda x: x[1])
        
query=[]
for i in range(Q):
    l, r=map(int, input().split())
    query.append((l,r,i))
query=sorted(query, key=lambda x: -x[1])

seg=BIT(N+1)
ans=[0]*Q



for i in range(len(que)):
    while query and query[-1][1]<que[i][1]:
        q=query.pop()
        l,r,j=q
        ans[j]=r-l+1-(seg.get(l-1,r))

    now=que[i]
    l, r=now  # index
    #A[l]+=1
    seg.add(l, 1)

    while query and query[-1][1]==r:
        q=query.pop()
        lq,rq,j=q
        
        ans[j]=rq-lq+1-(seg.get(lq-1,rq))
        #print(lq, rq, seg.query(lq,rq+1))
        #print(seg.get(lq,rq+1))

while query:
    q=query.pop()
    lq,rq,j=q     
    ans[j]=rq-lq+1-(seg.get(lq-1,rq))
    #print(lq, rq, seg.query(lq,rq+1))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from numba import njit, prange

N, Q = map(int, input().split())
C = np.asarray(list(map(int, input().split())))
LR = np.asarray([list(map(int, input().split())) for _ in range(Q)])

@njit('(i8, i8, i8[:], i8[:,:])', parallel=True)
def solve(N, Q, C, LR):
    ans = np.zeros(N, dtype=np.int64)
    for i in prange(Q):
        l, r = LR[i]
        used = np.zeros(N + 1, dtype=np.int32)

        for j in range(l - 1, r):
            if used[C[j]] == 0:
                ans[i] += 1
                used[C[j]] += 1

    for i in range(Q):
        print(ans[i])

solve(N, Q, C, LR)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
n,q = map(int,input().split())
arr = list(map(int,input().split()))
dd = defaultdict(lambda: -1)
brr = [0]
for i in range(n):
    brr.append(dd[arr[i]])
    dd[arr[i]]=i+1
for _ in range(q):
    l,r = map(int,input().split())
    ans = 0
    for i in range(l,r+1):
        if brr[i]<l:
            ans+=1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from numpy import array
n, k = array([int(i) for i in input().split()])
nums = array([int(i) for i in input().split()])
res = array([[-1]*n for i in range(n)])
for i in range(n):
    res[i][i] = 1
def dp(i, j):
    if res[i][j] != -1:
        return res[i][j]
    else:
        if nums[j] in nums[i:j]:
            tem = dp(i, j-1)
        else:
            tem = dp(i, j-1) + 1
    res[i][j] = tem
    return tem
for i in range(n):
    dp(i, n-1)
for i in range(k):
    i, j  = [int(i) for i in input().split()]
    print(res[i-1][j-1])

Submission status: Time Limit Exceeded

Solution code:
n,q = map(int,input().split(' '))
c = list(map(int,input().split(' ')))
data = [list(map(int,input().split(' '))) for _ in range(q)]

def make_set(lst):
    s = set(lst)
    return len(s)

for d in data:
    print(make_set(c[d[0]-1:d[1]]))