메모리: 31964 KB, 시간: 464 ms
조합론, 구현, 수학
2024년 12월 31일 22:22:42
1부터 N까지의 수로 이루어진 순열이 있다. 이때, 사전순으로 바로 이전에 오는 순열을 구하는 프로그램을 작성하시오.
사전 순으로 가장 앞서는 순열은 오름차순으로 이루어진 순열이고, 가장 마지막에 오는 순열은 내림차순으로 이루어진 순열이다.
N = 3인 경우에 사전순으로 순열을 나열하면 다음과 같다.
- 1, 2, 3
- 1, 3, 2
- 2, 1, 3
- 2, 3, 1
- 3, 1, 2
- 3, 2, 1
첫째 줄에 N(1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄에 순열이 주어진다.
첫째 줄에 입력으로 주어진 순열의 이전에 오는 순열을 출력한다. 만약, 사전순으로 가장 처음에 오는 순열인 경우에는 -1을 출력한다.
풀이
이전에 풀었던 문제에서 탐색 배열만 반대로 정렬해주었다.
https://2junbeom.tistory.com/158
백준 10972번 다음 순열 (java)
[Silver III] 다음 순열 - 10972문제 링크성능 요약메모리: 24596 KB, 시간: 408 ms분류조합론, 수학제출 일자2024년 12월 30일 19:47:05문제 설명1부터 N까지의 수로 이루어진 순열이 있다. 이때, 사전순으로 다
2junbeom.tistory.com
전체 코드
public class Main {
static int N;
static int[] x;
static int[] sorted;
static int flag = 0;
static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
x = new int[N];
sorted = new int[N];
visited = new boolean[N];
int srtV = N;
for (int i = 0; i < N; i++) {
x[i] = Integer.parseInt(st.nextToken());
sorted[i] = srtV-i;
}
dfs(new int[N], 0, N - x[0]);
System.out.println("-1");
}
public static void dfs(int[] re, int depth, int start){
if(depth == N){
if(flag == 1){
for (int i : re) {
System.out.print(i + " ");
}
exit(0);
}
if(check(re) && flag == 0){
flag = 1;
}
return;
}
for(int i=start;i<N;i++){
if(!visited[i]){
re[depth] = sorted[i];
visited[i] = true;
if(depth < N-1 && flag == 0) {
dfs(re, depth + 1, N - x[depth + 1]);
}
else{
dfs(re, depth + 1, 0);
}
visited[i] = false;
}
}
}
public static boolean check(int[] re){
for(int i = 0; i < N; i++){
if(re[i] != x[i]){
return false;
}
}
return true;
}
}
'코딩 테스트 연습 > 백준' 카테고리의 다른 글
백준 7562번 나이트의 이동 (java) (1) | 2025.04.11 |
---|---|
백준 10974번 모든 순열 (java) (0) | 2025.01.09 |
백준 10972번 다음 순열 (java) (0) | 2024.12.30 |
백준 1759번 암호 만들기 (java) (3) | 2024.12.28 |
백준 14501번 퇴사 (java) (0) | 2024.12.27 |