-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP10972_next_permutation.java
54 lines (46 loc) · 1.35 KB
/
P10972_next_permutation.java
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
package net.acmicpc.순열조합;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class P10972_next_permutation {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] num = new int[N];
String[] s = br.readLine().split(" ");
for (int i = 0; i < N; ++i) {
num[i] = Integer.parseInt(s[i]);
}
if (nextPermutation(num)) {
for (int i = 0; i < N; ++i) {
System.out.print(num[i] + " ");
}
System.out.println();
} else {
System.out.println(-1);
}
}
private static boolean nextPermutation(int[] num) {
int i = num.length - 1;
while (i > 0 && num[i - 1] >= num[i]) {
i -= 1;
}
if (i <= 0) return false;
int j = num.length - 1;
while (num[j] <= num[i - 1]) {
j -= 1;
}
int temp = num[i - 1];
num[i - 1] = num[j];
num[j] = temp;
j = num.length - 1;
while (i < j) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
i += 1;
j -= 1;
}
return true;
}
}