300x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 브루트포스
- PYTHON
- 코딩
- 네트워크
- OS
- linux
- 구글 킥스타트
- 백준
- nlp
- 딥러닝
- dp
- 코딩테스트
- 킥스타트
- 리눅스
- 동적 프로그래밍
- DFS
- kick start
- 코딩 테스트
- 프로그래머스
- 순열
- 알고리즘
- 운영체제
- AI
- google coding competition
- 그래프
- BFS
- 파이썬
- 프로그래밍
- 동적프로그래밍
- CSS
Archives
- Today
- Total
오뚝이개발자
[백준10973] 이전 순열 본문
728x90
300x250
문제
https://www.acmicpc.net/problem/10973
10973번: 이전 순열
첫째 줄에 입력으로 주어진 순열의 이전에 오는 순열을 출력한다. 만약, 사전순으로 가장 처음에 오는 순열인 경우에는 -1을 출력한다.
www.acmicpc.net
생각의 흐름
- 다음 순열 문제의 대소비교 부분을 반대로 생각하면 된다.
코드
def next_permutation(arr):
n = len(arr)-1
if n==0:
return -1
i = n
while arr[i-1] < arr[i]:
i -= 1
if i == 0:
return -1
j = i-1
diff = -10000
position_to_switch = 0
for k in range(i, n+1):
if arr[k]-arr[j] < 0:
diff = max(diff, arr[k]-arr[j])
for m in range(i, n+1):
if arr[m]==arr[j]+diff:
position_to_switch = m
break
temp = arr[j]
arr[j] = arr[position_to_switch]
arr[position_to_switch] = temp
temp_list = arr[j+1:]
temp_list.sort()
temp_list.reverse()
arr = arr[:j+1]
arr = arr + temp_list
#arr[j+1:].sort()
return arr
if __name__=='__main__':
num = int(input())
arr = list(map(int, input().split()))
result = next_permutation(arr)
if result == -1:
print(-1)
else:
for p in result:
print(p, end=' ')
728x90
300x250
'코딩 테스트 > 백준' 카테고리의 다른 글
[백준10819] 차이를 최대로 (0) | 2020.03.09 |
---|---|
[백준10974] 모든 순열 (0) | 2020.03.08 |
[백준10972] 다음 순열 (0) | 2020.03.08 |
[백준9095] 1, 2, 3 더하기 (0) | 2020.03.08 |
[백준14500] 테트로미노 (0) | 2020.03.08 |
Comments