티스토리 뷰

PS/boj

boj)10972 - 다음 순열

kingsubin 2020. 11. 30. 11:02
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.io.*;
import java.util.StringTokenizer;
 
public class boj_10972 {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer st;
    static int N;
    static int[] a;
 
    public static void main(String[] args) throws IOException {
        N = Integer.parseInt(br.readLine());
        a = new int[N];
 
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < a.length; i++) {
            a[i] = Integer.parseInt(st.nextToken());
        }
 
        if (next_Permutation(a, N)) {
            for (int i = 0; i < N; i++) {
                System.out.print(a[i] + " ");
            }
        } else {
            System.out.println(-1);
        }
    }
 
    static boolean next_Permutation(int[] a, int n) {
        int i = n-1;
        while (i > 0 && a[i-1>= a[i]) i-=1// 1.
        if (i <= 0return false// 마지막 순열
 
        int j = n-1// 2.
        while (a[j] <= a[i-1]) j-=1;
 
        // 3. swap(a[i-1], a[j]);
        int temp = a[i-1];
        a[i-1= a[j];
        a[j] = temp;
 
        j = n-1// 4.
        while (i < j) {
//            swap(a[i], a[j]);
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i += 1; j -= 1;
        }
        return true;
    }
}
 
cs

 

- 수학, 브루트포스

 

- 다음 순열을 구하는 next_permutation 에 대해서 혼자서는 구현할 방법이 생각이 안났다.

- 이제 배웠으니까 써먹을 수 있겠다.

 

* Next Permutation

  1. A[i-1] < A[i] 만족하는 가장 i 찾는다.
  2. j>=i이면서 A[j]>A[I-1] 만족하는 가장 j 찾는다.
  3. A[i-1] A[j] swap한다.
  4. A[i]부터 순열을 뒤집는다.

 

 

 

 


www.acmicpc.net/problem/10972

'PS > boj' 카테고리의 다른 글

boj)10974 - 모든 순열  (0) 2020.11.30
boj)10973 - 이전 순열  (0) 2020.11.30
boj)18808 - 스티커 붙이기  (0) 2020.11.27
boj)15683 - 감시  (0) 2020.11.25
boj)1182 - 부분수열의 합  (0) 2020.11.23