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: Accepted

Solution code:
N=2**20-1
R=range
(n,q),c,*z=[[*map(int,t.split())]for t in open(0)]
t,*o=B=[0]*N
A=[[n]for _ in B]
for i in R(n):A[c[~i]]+=~i+n,
def P(a,x):
	i=a[-1]+1
	while i<=n:B[i]+=x;i+=i&-i
for i in A:P(i,1)
for x in sorted(i|z[i][0]<<40|z[i][1]<<20for i in R(q)):
	l,r,i=(x>>40)-1,x>>20&N,x&N
	while t<l:b=A[c[t]];P(b,-1);b.pop();P(b,1);t+=1
	while r:o[i]+=B[r];r-=r&-r
	while l:o[i]-=B[l];l-=l&-l
print(*o[:q])

Submission status: Accepted

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def get_sum(bit, i):
    s = 0
    while i:
        s += bit[i]
        i -= i & -i
    return s

def add(bit, i, x):
    while i < len(bit):
        bit[i] += x
        i += i & -i

def main(A, LR):
    N = len(A)
    L, R = LR[::2], LR[1::2]
    Q = len(L)
    query_order = np.argsort(R)
    L, R = L[query_order], R[query_order]
    ind = np.searchsorted(R, np.arange(N + 2))
    right_end = np.zeros(N + 1, np.int64)
    bit = np.zeros(N + 1, np.int64)
    answers = np.empty(Q, np.int64)
    for r in range(1, N + 1):
        a = A[r - 1]
        p = right_end[a]
        if p:
            add(bit, p, -1)
        right_end[a] = r
        add(bit, r, 1)
        for i in range(ind[r], ind[r + 1]):
            l, r, i = L[i], R[i], query_order[i]
            answers[i] = get_sum(bit, r) - get_sum(bit, l - 1)
    return answers

if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    i4 = numba.int32
    i8 = numba.int64
    cc = CC('my_module')

    def cc_export(f, signature):
        cc.export(f.__name__, signature)(f)
        return numba.njit(f)

    get_sum = cc_export(get_sum, (i8[:], i8))
    add = cc_export(add, (i8[:], i8, i8))
    main = cc_export(main, (i8[:], i8[:]))
    cc.compile()

from my_module import main

N, Q = map(int, readline().split())
A = np.array(readline().split(), np.int64)
LR = np.array(read().split(), np.int64)

ans = main(A, LR)
print('\n'.join(map(str, ans.tolist())))

Submission status: Accepted

Solution code:
import sys
import numpy as np
import numba
from numba import njit
from numba.types import Omitted
i4 = numba.int32
i8 = numba.int64

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8[:], i8), cache=True)
def get_sum(bit, i):
    s = 0
    while i:
        s += bit[i]
        i -= i & -i
    return s


@njit((i8[:], i8, i8), cache=True)
def add(bit, i, x):
    while i < len(bit):
        bit[i] += x
        i += i & -i

@njit((i8[:], i8[:]), cache=True)
def main(A, LR):
    N = len(A)
    L, R = LR[::2], LR[1::2]
    Q = len(L)
    query_order = np.argsort(R)
    L, R = L[query_order], R[query_order]
    ind = np.searchsorted(R, np.arange(N + 2))
    right_end = np.zeros(N + 1, np.int64)
    bit = np.zeros(N + 1, np.int64)
    answers = np.empty(Q, np.int64)
    for r in range(1, N + 1):
        a = A[r - 1]
        p = right_end[a]
        if p:
            add(bit, p, -1)
        right_end[a] = r
        add(bit, r, 1)
        for i in range(ind[r], ind[r + 1]):
            l, r, i = L[i], R[i], query_order[i]
            answers[i] = get_sum(bit, r) - get_sum(bit, l - 1)
    return answers

N, Q = map(int, readline().split())
A = np.array(readline().split(), np.int64)
LR = np.array(read().split(), np.int64)

ans = main(A, LR)
print('\n'.join(map(str, ans.tolist())))

Submission status: Accepted

Solution code:
import sys
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=lambda x:x[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: Accepted

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

Bsize = 1333

def Mo_argsort(LR):
    L = LR[:, 0]
    R = LR[:, 1]
    key1 = L // Bsize
    key2 = np.where(key1 & 1, -R, R)
    key = (key1 << 32) + key2
    return np.argsort(key)

def main(A, LR):
    N = len(A)
    Q = len(LR)
    ind = Mo_argsort(LR)
    count = np.zeros(N + 1, np.int64)
    ans = 0

    def add(x):
        nonlocal ans
        if not count[x]:
            ans += 1
        count[x] += 1

    def rem(x):
        nonlocal ans
        count[x] -= 1
        if not count[x]:
            ans -= 1

    answers = np.empty(Q, np.int64)
    nl, nr = 0, 0
    for i in ind:
        l, r = LR[i]
        l -= 1
        # 区間 [l, r) に対する計算
        while nl > l:
            nl -= 1
            add(A[nl])
        while nr < r:
            add(A[nr])
            nr += 1
        while nl < l:
            rem(A[nl])
            nl += 1
        while nr > r:
            nr -= 1
            rem(A[nr])
        #  答を求めて ans[i] に格納する
        answers[i] = ans
    return answers

if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    i4 = numba.int32
    i8 = numba.int64
    cc = CC('my_module')

    def cc_export(f, signature):
        cc.export(f.__name__, signature)(f)
        return numba.njit(f)

    Mo_argsort = cc_export(Mo_argsort, (i8[:,:],))
    main = cc_export(main, (i8[:], i8[:, :]))
    cc.compile()

from my_module import main

N, Q = map(int, readline().split())
A = np.array(readline().split(), np.int64)
LR = np.array(read().split(), np.int64).reshape(Q, 2)

ans = main(A, LR)
print('\n'.join(map(str, ans.tolist())))

Submission status: Accepted

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

Bsize = 1000

def Mo_argsort(LR):
    L = LR[:, 0]
    R = LR[:, 1]
    key1 = L // Bsize
    key2 = np.where(key1 & 1, -R, R)
    key = (key1 << 32) + key2
    return np.argsort(key)

def main(A, LR):
    N = len(A)
    Q = len(LR)
    ind = Mo_argsort(LR)
    count = np.zeros(N + 1, np.int64)
    ans = 0

    def add(x):
        nonlocal ans
        if not count[x]:
            ans += 1
        count[x] += 1

    def rem(x):
        nonlocal ans
        count[x] -= 1
        if not count[x]:
            ans -= 1

    answers = np.empty(Q, np.int64)
    nl, nr = 0, 0
    for i in ind:
        l, r = LR[i]
        l -= 1
        # 区間 [l, r) に対する計算
        while nl > l:
            nl -= 1
            add(A[nl])
        while nr < r:
            add(A[nr])
            nr += 1
        while nl < l:
            rem(A[nl])
            nl += 1
        while nr > r:
            nr -= 1
            rem(A[nr])
        #  答を求めて ans[i] に格納する
        answers[i] = ans
    return answers

if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    i4 = numba.int32
    i8 = numba.int64
    cc = CC('my_module')

    def cc_export(f, signature):
        cc.export(f.__name__, signature)(f)
        return numba.njit(f)

    Mo_argsort = cc_export(Mo_argsort, (i8[:,:],))
    main = cc_export(main, (i8[:], i8[:, :]))
    cc.compile()

from my_module import main

N, Q = map(int, readline().split())
A = np.array(readline().split(), np.int64)
LR = np.array(read().split(), np.int64).reshape(Q, 2)

ans = main(A, LR)
print('\n'.join(map(str, ans.tolist())))

Submission status: Accepted

Solution code:
def position_zip(a,flag):
  j=0
  d={}
  for i in sorted(a):
    if i in d:continue
    d[i]=j
    j+=1
  if flag==1:return d
  return [d[i] for i in a]
class BinaryIndexedTree:
  def __init__(self,n):
    self.bit=[0]*n
  def add(self,i,x):
    i+=1
    while i<=len(self.bit):
      self.bit[i-1]+=x
      i+=i&-i
  def sum_sub(self,i):
    a=0
    i+=1
    while i:
      a+=self.bit[i-1]
      i-=i&-i
    return a
  def sum(self,i,j):
    a=self.sum_sub(j+1)
    if i!=0:a-=self.sum_sub(i-1)
    return a
xx=1<<20
n,q=map(int,input().split())
a=list(map(int,input().split()))
a=position_zip(a,0)
k=max(a)+1
ans=[0]*q
queries=[]
for i in range(q):
  l,r=list(map(int,input().split()))
  l-=1
  r-=1
  queries.append(r<<40|l<<20|i)
queries.sort()
for i in range(q):
  ind=queries[i]%xx
  queries[i]>>=20
  l=queries[i]%xx
  queries[i]>>=20
  r=queries[i]
  queries[i]=(r,l,ind)
queries.append((10*20,0,0))
lastAppeared=[-1]*k
bitt=BinaryIndexedTree(n)
j=0
for i in range(n):
  if lastAppeared[a[i]]!=-1:
    bitt.add(lastAppeared[a[i]],-1)
    bitt.add(i,1)
    lastAppeared[a[i]]=i
  else:
    bitt.add(i,1)
    lastAppeared[a[i]]=i
  while queries[j][0]==i:
    r,l,ind=queries[j]
    j+=1
    ans[ind]=bitt.sum(l,r-1)
print(*ans)

Submission status: Accepted

Solution code:
def main():
  def add(i,x):
    i+=1
    while i<=n:
      bit[i-1]+=x
      i+=i&-i
  def sum_sub(i):
    a=0
    i+=1
    while i:
      a+=bit[i-1]
      i-=i&-i
    return a
  def sum(i,j):
    a=sum_sub(j+1)
    if i!=0:a-=sum_sub(i-1)
    return a
  
  n,q,*x=map(int,open(0).read().split())
  a=x[:n]
  queriess=[]
  for i in range(q):
    l,r=x[n+i*2:n+(i+1)*2]
    l-=1
    r-=1
    queriess.append(r<<40|l<<20|i)
  ans=[0]*q
  queriess.sort()
  queries=[]
  for i in range(q):
    ind=queriess[i]%(1<<20)
    queriess[i]>>=20
    l=queriess[i]%(1<<20)
    queriess[i]>>=20
    r=queriess[i]
    queries.append((r,l,ind))
  queries.append((10*20,0,0))
  lastAppeared=[-1]*n
  bit=[0]*n
  j=0
  for i in range(n):
    if lastAppeared[a[i]-1]!=-1:
      add(lastAppeared[a[i]-1],-1)
      add(i,1)
      lastAppeared[a[i]-1]=i
    else:
      add(i,1)
      lastAppeared[a[i]-1]=i
    while queries[j][0]==i:
      r,l,ind=queries[j]
      j+=1
      ans[ind]=sum(l,r-1)
  print(*ans)
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
def main():
  def add(i,x):
    i+=1
    while i<=n:
      bit[i-1]+=x
      i+=i&-i
  def sum_sub(i):
    a=0
    i+=1
    while i:
      a+=bit[i-1]
      i-=i&-i
    return a
  def sum(i,j):
    a=sum_sub(j+1)
    if i!=0:a-=sum_sub(i-1)
    return a
  
  n,q,*x=map(int,open(0).read().split())
  a=x[:n]
  queries=[]
  for i in range(q):
    l,r=x[n+i*2:n+(i+1)*2]
    l-=1
    r-=1
    queries.append(r<<40|l<<20|i)
  ans=[0]*q
  queries.sort()
  for i in range(q):
    ind=queries[i]%(1<<20)
    queries[i]>>=20
    l=queries[i]%(1<<20)
    queries[i]>>=20
    r=queries[i]
    queries[i]=[r,l,ind]
  queries.append([10*20])
  lastAppeared=[-1]*n
  bit=[0]*n
  j=0
  for i in range(n):
    if lastAppeared[a[i]-1]!=-1:
      add(lastAppeared[a[i]-1],-1)
      add(i,1)
      lastAppeared[a[i]-1]=i
    else:
      add(i,1)
      lastAppeared[a[i]-1]=i
    while queries[j][0]==i:
      r,l,ind=queries[j]
      j+=1
      ans[ind]=sum(l,r-1)
  print(*ans)
if __name__ == "__main__":
  main()

Submission status: Accepted

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: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[0]*Q
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=(r<<40)+(l<<20)+i
lr.sort(reverse=1)
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
mask=(1<<20)-1
lr_pop=lr.pop
lrj=lr_pop()
j=lrj&mask
lrj>>=20
l=lrj&mask
r=lrj>>20
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:            
            lrj=lr_pop()
            j=lrj&mask
            lrj>>=20
            l=lrj&mask
            r=lrj>>20
        else:
            l,r,j=-1,-1,-1
print(*ans,sep='\n')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[0]*Q
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=(r<<40)+(l<<20)+i
lr.sort(reverse=1)
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
mask=(1<<20)-1
lrj=lr.pop()
j=lrj&mask
lrj>>=20
l=lrj&mask
r=lrj>>20
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:            
            lrj=lr.pop()
            j=lrj&mask
            lrj>>=20
            l=lrj&mask
            r=lrj>>20
        else:
            l,r,j=-1,-1,-1
print(*ans,sep='\n')

Submission status: Accepted

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+1:
        lq,rq,j=query.pop()
        ans[j]=rq-lq+1-(seg.get(lq-1,rq))
        #print(lq, rq, seg.get(lq-1,rq))



for a in ans:
    print(a)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[() for i in range(Q)]
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=(l,r,i)
lr.sort(key=lambda t: t[1],reverse=1)
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
l,r,j=lr.pop()
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:
            l,r,j=lr.pop()
        else:
            l,r,j=-1,-1,-1
print(*ans,sep='\n')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[() for i in range(Q)]
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=(l,r,i)
lr.sort(key=lambda t: -t[1])
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
l,r,j=lr.pop()
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:
            l,r,j=lr.pop()
        else:
            l,r,j=-1,-1,-1
print(*ans,sep='\n')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[0]*Q
c0=10**12
c1=10**6
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=r*c0+l*c1+i
lr.sort(reverse=1)
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
lrj=lr.pop()
r=lrj//c0
lrj%=c0
l=lrj//c1
j=lrj%c1
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:            
            lrj=lr.pop()
            r=lrj//c0
            lrj%=c0
            l=lrj//c1
            j=lrj%c1
        else:
            l,r,j=-1,-1,-1
print(*ans,sep='\n')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[() for i in range(Q)]
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=(l,r,i)
lr.sort(key=lambda t: t[1],reverse=1)
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
l,r,j=lr.pop()
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:
            l,r,j=lr.pop()
        else:
            l,r,j=-1,-1,-1
print(*ans,sep='\n')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,Q=map(int,input().split())
a=tuple(map(int1,input().split()))
lr=[() for i in range(Q)]
for i in range(Q):
    l,r=map(int1,input().split())
    lr[i]=(l,r,i)
lr.sort(key=lambda t: t[1],reverse=1)
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
    
    def lower_bound(self,x):
        sum_=0
        pos=0
        for i in range(self.depth,-1,-1):
            k=pos+(1<<i)
            if k<=self.num and sum_+self.dat[k]<x:
                sum_+=self.dat[k]
                pos+=1<<i
        return pos, sum_

b=BIT(N)
lastap=[-1]*N
ans=[-1]*Q
l,r,j=lr.pop()
for i,x in enumerate(a):
    if lastap[x]!=-1:
        b.add(lastap[x],-1)
    b.add(i,1)
    lastap[x]=i
    while r==i:
        ans[j]=b.sum(r)-b.sum(l-1)
        if lr:
            l,r,j=lr.pop()
        else:
            l,r,j=-1,-1,-1
for x in ans:
    print(x)

Submission status: Accepted

Solution code:
I=lambda:map(int,input().split())
N=0xfffff
n,q=I()
c=list(I())
Q=[]
R=range
for i in R(q):l,r=I();Q.append(l<<40|r<<20|i)
Q.sort()
A=[[n]for i in R(N)]
for i in R(n)[::-1]:A[c[i]].append(i)
B=[0]*N
def P(a,x):
	i=a[-1]
	i+=1
	while i<=n:B[i]+=x;i+=i&-i
for i in A:P(i,1)
t=0
o=[0]*q
for x in Q:
	l=(x>>40)-1
	r=x>>20&N
	i=x&N
	while t<l:b=A[c[t]];P(b,-1);b.pop();P(b,1);t+=1
	while r:o[i]+=B[r];r-=r&-r
	while l:o[i]-=B[l];l-=l&-l
for i in o:print(i)

Submission status: Accepted

Solution code:
I=lambda:map(int,input().split())
N=0xfffff
n,q=I()
c=list(I())
Q=[]
R=range
for i in R(q):l,r=I();Q.append(l<<40|r<<20|i)
Q.sort()
A=[[n]for i in R(N)]
for i in R(n)[::-1]:A[c[i]].append(i)
B=[0]*N
def P(a,x):
	i=a[-1]
	i+=1
	while i<=n:B[i]+=x;i+=i&-i
for i in A:P(i,1)
t=0
o=[0]*q
for x in Q:
	l=(x>>40)-1
	r=x>>20&N
	i=x&N
	while t<l:
		b=A[c[t]]
		P(b,-1)
		b.pop()
		P(b,1)
		t+=1
	while r:o[i]+=B[r];r-=r&-r
	while l:o[i]-=B[l];l-=l&-l
for i in o:print(i)

Submission status: Accepted

Solution code:
I=lambda:map(int,input().split())
N=0xfffff
n,q=I()
c=list(I())
Q=[]
R=range
for i in R(q):l,r=I();Q.append(l<<40|r<<20|i)
Q.sort()
A=[[n]for i in R(N)]
for i in R(n)[::-1]:A[c[i]].append(i)
B=[0]*N
def P(i,x):
	i+=1
	while i<=n:B[i]+=x;i+=i&-i
for i in A:P(i[-1],1)
t=0
o=[0]*q
for x in Q:
	l=(x>>40)-1
	r=x>>20&N
	i=x&N
	while t<l:
		b=A[c[t]]
		P(b[-1],-1)
		b.pop()
		P(b[-1],1)
		t+=1
	while r:o[i]+=B[r];r-=r&-r
	while l:o[i]-=B[l];l-=l&-l
for i in o:print(i)

Submission status: Accepted

Solution code:
def solve():
    import sys
    input = sys.stdin.readline

    class BIT:
        def __init__(self, n):
            self.n = n
            self.data = [0] * n

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

        def update(self, i, x):
            while i < self.n:
                self.data[i] += x
                i |= i + 1

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

    b = BIT(n)
    diff = 0
    ans = [-1] * q
    last = [-1] * (n + 1)

    for i, v in enumerate(c):
        if last[v] != -1:
            b.update(last[v], -1)
        else:
            diff += 1

        b.update(i, 1)
        last[v] = i

        for l, j in odr_r[i + 1]:
            ans[j] = diff - b.sum(l)
    print("\n".join(map(str, ans)))
    return


solve()

Submission status: Accepted

Solution code:
I=lambda:map(int,input().split())
N=0xfffff
n,q=I()
c=list(I())
Q=[]
R=range
for i in R(q):l,r=I();Q.append(l<<40|r<<20|i)
Q.sort()
A=[[]for i in R(N)]
for i in R(n):A[c[i]].append(i)
B=[0]*N
def P(i,x):
	i+=1
	while i<=n:B[i]+=x;i+=i&-i
for i in A:
	if i:P(i[0],1);i.reverse()
t=0
o=[0]*q
for x in Q:
	l=(x>>40)-1
	r=x>>20&N
	i=x&N
	while t<l:
		b=A[c[t]]
		P(b[-1],-1)
		b.pop()
		if b:P(b[-1],1)
		t+=1
	while r:o[i]+=B[r];r-=r&-r
	while l:o[i]-=B[l];l-=l&-l
for i in o:print(i)

Submission status: Accepted

Solution code:
I=lambda:map(int,input().split())
N=0xfffff
n,q=I()
c=list(I())
Q=[]
R=range
for i in R(q):l,r=I();Q.append(l<<40|r<<20|i)
Q.sort()
A=[[]for i in R(N)]
for i in R(n):A[c[i]].append(i)
B=[0]*N
def P(i,x):
	i+=1
	while i<=n:B[i]+=x;i+=i&-i
def G(i):
	s=0
	while i:s+=B[i];i-=i&-i
	return s
for i in A:
	if i:P(i[0],1);i.reverse()
t=0
o=[0]*q
for x in Q:
	l=x>>40
	r=x>>20&N
	i=x&N
	while t+1<l:
		b=A[c[t]]
		P(b[-1],-1)
		b.pop()
		if b:P(b[-1],1)
		t+=1
	o[i]=G(r)-G(l-1)
for i in o:print(i)

Submission status: Accepted

Solution code:
I=lambda:map(int,input().split())
N=0xfffff
n,q=I()
c=list(I())
Q=[]
for i in range(q):l,r=I();Q.append(l<<40|r<<20|i)
Q.sort()
A=[[]for i in range(N)]
for i in range(n):A[c[i]].append(i)
B=[0]*N
def P(i,x):
	i+=1
	while i<=n:B[i]+=x;i+=i&-i
def G(i):
	s=0
	while i:s+=B[i];i-=i&-i
	return s
for i in A:
	if i:P(i[0],1);i.reverse()
t=0
o=[0]*q
for x in Q:
	l=x>>40
	r=x>>20&N
	i=x&N
	while t+1<l:
		b=A[c[t]]
		P(b[-1],-1)
		b.pop()
		if b:P(b[-1],1)
		t+=1
	o[i]=G(r)-G(l-1)
for i in o:print(i)