목차

수열과 쿼리 5

ps
링크acmicpc.net/…
출처BOJ
문제 번호13547
문제명수열과 쿼리 5
레벨플래티넘 2
분류

구간 쿼리

시간복잡도O(n+mlogn)
인풋사이즈n<=100,000, m<=100,000
사용한 언어Python
제출기록75264KB / 1236ms
최고기록1132ms
해결날짜2021/05/04
태그

48단계

풀이

코드

"""Solution code for "BOJ 13547. 수열과 쿼리 5".

- Problem link: https://www.acmicpc.net/problem/13547
- Solution link: http://www.teferi.net/ps/problems/boj/13547
"""

import sys
from teflib import fenwicktree


def main():
    N = int(sys.stdin.readline())
    A = [int(x) for x in sys.stdin.readline().split()]
    queries = [[] for _ in range(N)]
    M = int(sys.stdin.readline())
    for query_num in range(M):
        i, j = [int(x) for x in sys.stdin.readline().split()]
        queries[j - 1].append((i - 1, query_num))

    last_pos = dict()
    fenwick = fenwicktree.FenwickTree(N)
    answers = [None] * M
    for i, a_i in enumerate(A):
        try:
            fenwick.update(last_pos[a_i], -1)
        except KeyError:
            pass
        fenwick.update(i, 1)
        last_pos[a_i] = i
        for l, query_num in queries[i]:
            answers[query_num] = fenwick.query(l, i + 1)

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


if __name__ == '__main__':
    main()