목차

최솟값

ps
링크acmicpc.net/…
출처BOJ
문제 번호10868
문제명최솟값
레벨골드 1
분류

구간 쿼리

시간복잡도O(α(n)*(n+q))
인풋사이즈n<=100,000, q<=100,000
사용한 언어Python
제출기록71076KB / 604ms
최고기록604ms
해결날짜2021/02/21

풀이

코드

"""Solution code for "BOJ 10868. 최솟값".

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

import collections
import sys
from teflib import disjointset


def main():
    N, M = [int(x) for x in sys.stdin.readline().split()]
    nums = [int(sys.stdin.readline()) for _ in range(N)]
    queries = [[] for _ in range(N)]
    answers = [0] * M
    for i in range(M):
        a, b = [int(x) for x in sys.stdin.readline().split()]
        queries[b - 1].append((a - 1, i))

    IndexAndVal = collections.namedtuple('IndexAndVal', 'index val')
    dset = disjointset.DisjointSet(N)
    min_by_set = nums[:]
    stack = []
    for i, num_i in enumerate(nums):
        while stack and stack[-1].val > num_i:
            set_id = dset.union(stack.pop().index, i)
            min_by_set[set_id] = num_i
        stack.append(IndexAndVal(i, num_i))
        for left, query_num in queries[i]:
            answers[query_num] = min_by_set[dset.find(left)]

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


if __name__ == '__main__':
    main()