백준 알고리즘
[백준/Python] 10973_이전 순열
헝그리개발자
2021. 6. 22. 12:57
문제
https://www.acmicpc.net/problem/10973
10973번: 이전 순열
첫째 줄에 입력으로 주어진 순열의 이전에 오는 순열을 출력한다. 만약, 사전순으로 가장 처음에 오는 순열인 경우에는 -1을 출력한다.
www.acmicpc.net
풀이
next_permutation 알고리즘의 부등호만 바꾸면 이전 순열을 구현할 수 있습니다.
코드
import sys
def prev_permutation(lst):
l = len(lst)
x = -1
for i in range(l - 2, -1, -1):
if lst[i] > lst[i + 1]:
x = i
break
if x == -1:
return [-1]
for j in range(l - 1, x, -1):
if lst[x] > lst[j]:
lst[x], lst[j] = lst[j], lst[x]
break
return lst[:x + 1] + lst[:x:-1]
n = int(sys.stdin.readline().rstrip())
case = list(map(int, sys.stdin.readline().rstrip().split()))
answer = prev_permutation(case)
print(' '.join(map(str, answer)))