티스토리 뷰
문제 링크 : https://www.acmicpc.net/problem/10972
10972번: 다음 순열
첫째 줄에 입력으로 주어진 순열의 다음에 오는 순열을 출력한다. 만약, 사전순으로 마지막에 오는 순열인 경우에는 -1을 출력한다.
www.acmicpc.net
가장 마지막에 오는 것은 내림차순이라는 문제의 설명이 모든 것을 말해 주고 있다.
N=5 인 경우 즉, 1 2 3 4 5 로 이루어지는 한 순열을 관찰해 보자.
1. 순열에서 가장 긴 내림차순으로 이루어진 마지막 부분(suffix)을 찾았을 때,
앞 부분이 2 3 으로 시작되는 순열의 마지막임을 알게 된다.
그렇다면 앞 부분 2 3 을 바꾸어야 할 것이다.
2. 뒤의 5 4 1 중에서 3 보다 큰 첫 수를 찾아서 바꾸어야 한다.
3. 2의 결과 앞 부분은 2 3 에서 2 4 로 바뀌고 뒷 부분은 1 3 5 로 두고 새로이 순열을 구성한다.
위의 1, 2, 3 단계를 일반화시키면 문제는 해결된다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
int N, arr[10001]; | |
int main(){ | |
scanf("%d",&N); | |
for(int i=0;i<N;i++) scanf("%d",&arr[i]); | |
// 1. 가장 긴 내림차순 suffix 를 찾는다. | |
int a=-1; | |
for(int i=N-1;i>0;i--) | |
if(arr[i-1]<arr[i]){ | |
a=i-1; | |
break; | |
} | |
if(a==-1) { | |
printf("-1\n"); | |
return 0; | |
} | |
// 2. 앞 부분의 마지막 수와 바꿀 내림차순 suffix 내부의 수를 찾는다. | |
int b=N-1; | |
while(arr[a]>arr[b]) | |
b--; | |
swap(arr[a],arr[b]); // 3. 두 수를 교체한다. | |
vector<int> res; | |
for(int i=0;i<=a;i++) res.push_back(arr[i]); | |
for(int i=N-1;i>a;i--) res.push_back(arr[i]); // 4. 뒷 부분을 오름차순으로 | |
for(int i=0;i<N;i++) | |
printf("%d ", res[i]); | |
printf("\n"); | |
} |
반응형
'DS\Algo > Mathematics' 카테고리의 다른 글
BOJ 10973 이전 순열 (0) | 2022.11.11 |
---|---|
BOJ 2981 GRANICA ( 검문 ) (1) | 2022.10.14 |
BOJ 10826 피보나치 수 4 (0) | 2022.10.02 |
BOJ 11049 행렬 곱셈 순서 (2) | 2022.09.20 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- fenwick tree
- lazy propagation
- C++ big number
- Reference
- map
- script
- dynamic programming
- shell
- max flow
- python3
- JavaScript
- stack
- segment tree
- RUBY
- number theory
- persistent segment tree
- 백준
- 다익스트라
- math font
- 세그먼트 트리
- Aho-Corasick
- Dijkstra
- 정수론
- BOJ
- Vim
- Shell Programming
- bash
- nearest common ancestor
- bash script
- javascript array
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함