목차

데크 소트

ps
링크acmicpc.net/…
출처BOJ
문제 번호1624
문제명데크 소트
레벨플래티넘 1
분류

그리디

시간복잡도O(nlogn)
인풋사이즈n<=1000
사용한 언어Python
제출기록32404KB / 88ms
최고기록72ms
해결날짜2022/01/26

풀이

코드

"""Solution code for "BOJ 1624. 데크 소트".

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

Tags: [Greedy]
"""

import collections
import sys

INF = float('inf')


def main():
    N = int(sys.stdin.readline())
    nums = [int(sys.stdin.readline()) for _ in range(N)]

    left_and_right_pos = collections.defaultdict(lambda: (INF, 0))
    for pos, num in enumerate(nums):
        l, r = left_and_right_pos[num]
        left_and_right_pos[num] = (min(l, pos), max(r, pos))

    answer = 0
    left_of_decreasing, right_of_increasing = None, INF
    for _, (l, r) in sorted(left_and_right_pos.items()):
        if right_of_increasing is None:
            if r < left_of_decreasing:
                left_of_decreasing = l
            else:
                right_of_increasing = r
        else:
            if l > right_of_increasing:
                right_of_increasing = r
            else:
                answer += 1
                left_of_decreasing, right_of_increasing = l, None

    print(answer)


if __name__ == '__main__':
    main()