SyntaxHighlighter.all(); [Java]백준 10973 이전순열 :: 게을러지고 싶어 부지런한 개발자
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
53
54
55
56
57
58
59
 
//이전 순열
public class Baekjoon10973 {
 
    public static void main(String[] args) throws NumberFormatException, IOException {
    
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        
        int arr[] = new int[N];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        
        if(prePermutation(arr)) {
            for (int i = 0; i < N; i++) {
                System.out.print(arr[i] + " ");
            }
            System.out.println();
        } else {
            System.out.println("-1");
        }
    }    
 
    public static boolean prePermutation(int[] arr) {
        
        //뒤에서부터 탐색해서 a-1가 a보다 큰 경우 찾음
        int a = arr.length - 1;
        while(a > 0 && arr[a-1<= arr[a]) a--;
        if (a <= 0return false;
        
        //다시 뒤에서부터 탐색하며 a-1가 b보다 큰 경우 찾음
        int b = arr.length - 1;
        while(arr[a-1<= arr[b]) b--;
        
        //a-1와 b를 swap
        int tmp = arr[a-1];
        arr[a-1= arr[b];
        arr[b] = tmp;
        
        //a부터 끝까지 내림차순 정렬 (swap이용) 
        int start = a;
        int end = arr.length - 1;
        while(start < end) {
            tmp = arr[start];
            arr[start] = arr[end];
            arr[end] = tmp;
            start++;
            end--;
        }
        return true;
    }
}

+ Recent posts