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
- 코딩
- DFS
- linux
- CSS
- 동적 프로그래밍
- 프로그래머스
- 운영체제
- 구글 킥스타트
- nlp
- 순열
- 그래프
- dp
- 백준
- kick start
- AI
- 동적프로그래밍
- 코딩 테스트
- BFS
- PYTHON
- 프로그래밍
- 코딩테스트
- google coding competition
- 브루트포스
- 파이썬
- OS
- 리눅스
- 킥스타트
- 네트워크
- 알고리즘
- 딥러닝
Archives
- Today
- Total
오뚝이개발자
[백준10972] 다음 순열 본문
728x90
300x250
문제
https://www.acmicpc.net/problem/10972
10972번: 다음 순열
첫째 줄에 입력으로 주어진 순열의 다음에 오는 순열을 출력한다. 만약, 사전순으로 마지막에 오는 순열인 경우에는 -1을 출력한다.
www.acmicpc.net
생각의 흐름
- 다음 순열을 어떻게 찾아낼까? (규칙성)
- 일의 자리부터 시작하여 바로 앞의 수보다 큰지 작은지를 비교하여 판별한다.
깨달은 점
- 사실 파이썬에는 이러한 기능을 구현해주는 permutations라는 아주 편리한 라이브러리가 있다...하지만, 구현을 해보는 데에 의의가 있으니^^
코드
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 = min(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()
arr = arr[:j+1]
arr = arr + temp_list
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
'코딩 테스트 > 백준' 카테고리의 다른 글
[백준10974] 모든 순열 (0) | 2020.03.08 |
---|---|
[백준10973] 이전 순열 (0) | 2020.03.08 |
[백준9095] 1, 2, 3 더하기 (0) | 2020.03.08 |
[백준14500] 테트로미노 (0) | 2020.03.08 |
[백준1476] 날짜 계산 (0) | 2020.03.05 |