목차

정렬하기

ps
링크acmicpc.net/…
출처BOJ
문제 번호16219
문제명정렬하기
레벨골드 4
분류

애드혹

시간복잡도O(n+m)
인풋사이즈n<=2*10^5, m<=6*10^5
사용한 언어Python 3.13
제출기록150768KB / 680ms
최고기록680ms
해결날짜2026/02/08

풀이

코드

"""Solution code for "BOJ 16219. 정렬하기".

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

Tags: [ad hoc]
"""

import sys


def main():
    N = int(sys.stdin.readline())
    S = [int(x) for x in sys.stdin.readline().split()]
    M = int(sys.stdin.readline())
    X_and_Y = [[int(x) for x in sys.stdin.readline().split()] for _ in range(M)]

    misplaced_count = sum(1 for i, x in enumerate(S) if i != x)
    answers = []
    for x, y in X_and_Y:
        if S[x] == x:
            misplaced_count += 1
        if S[y] == y:
            misplaced_count += 1
        if S[x] == y:
            misplaced_count -= 1
        if S[y] == x:
            misplaced_count -= 1
        S[x], S[y] = S[y], S[x]

        if misplaced_count == 0:
            answers.append('0')
        else:
            answers.append('-1' if N >= 3 else '1')

    print(' '.join(answers))


if __name__ == '__main__':
    main()