https://www.acmicpc.net/problem/10973
10973번: 이전 순열
첫째 줄에 입력으로 주어진 순열의 이전에 오는 순열을 출력한다. 만약, 사전순으로 가장 처음에 오는 순열인 경우에는 -1을 출력한다.
www.acmicpc.net
이전에 풀었던 다음 순열 문제를 조금만 변형하면 되는 문제다. 전체적인 알고리즘 논리는 같다. 부등호 방향만 반대로 해주면 된다.
import java.util.*;
public class Main {
public static void swap(int [] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean nextPermutation(int[] a) {
int i = a.length-1;
//뒤에서부터 a[i-1] > a[i]인 첫번째 부분을 찾는다.
while (i > 0 && a[i-1] < a[i]) {
i--;
if(i==0) break;
}
//i가 0이면 위의 루프를 다 돌았다는 의미 = 이미 오름차순으로 정렬되어 있음
if (i <= 0) {
return false;
}
//a[i..last] 중 a[i-1]보다 작은 수를 뒤에서부터 탐색
int j = a.length-1;
while (a[j] >= a[i-1]) {
j--;
}
//a[i-1]과 a[j]의 자리를 바꿈
swap(a, i-1, j);
//a[i..last]까지 내림차순 정렬
j = a.length-1;
while (i < j) {
swap(a, i, j);
i--; j++;
}
return true;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = sc.nextInt();
}
if (nextPermutation(a)) {
for (int i=0; i<n; i++) {
System.out.print(a[i] + " ");
}
}
else {
System.out.println("-1");
}
}
}
'프로그래밍 > 백준 문제풀이' 카테고리의 다른 글
백준 1182: 부분수열의 합 (1) | 2022.11.17 |
---|---|
백준 10974: 모든 순열 (0) | 2022.10.13 |
백준 10972: 다음 순열(JAVA) (0) | 2022.10.12 |
백준 9095번: 1, 2, 3 더하기 (0) | 2022.10.03 |
백준 1748: 수 이어 쓰기 1 (0) | 2022.10.03 |