44import java .util .*;
55
66public class Main {
7- static int step = 0 ;
8- static int sameIdx = 0 ;
9- static List < int []> result = new ArrayList <>();
7+ static int N ;
8+ static int [] num ;
9+
1010 public static void main (String [] args ) throws IOException {
1111 BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
12- int N =Integer .parseInt (br .readLine ());
13- int [] num = new int [N ];
12+ N = Integer .parseInt (br .readLine ());
13+ num = new int [N ];
1414 StringTokenizer st = new StringTokenizer (br .readLine ());
15- int idx = 0 ;
16- while (st .hasMoreTokens ()){
17- num [idx ]+= Integer .parseInt (st .nextToken ());
15+ int idx = 0 ;
16+ while (st .hasMoreTokens ()) {
17+ num [idx ] += Integer .parseInt (st .nextToken ());
1818 idx ++;
1919 }
20- int [] visited =new int [N ];
21- int [] find =new int [N ];
22- perm (visited , find , num , N ,0 ,0 );
20+ // 5 4 3 2 1
21+ //0
22+ //
23+ if (perm ()) {
24+ for (int i = 0 ; i < N ; i ++) {
25+ System .out .println (num [i ]+" " );
26+ }
27+ }else {
28+ System .out .println (-1 );
29+ }
30+
31+
32+ }
33+
34+ private static boolean perm () {
35+
36+ //먼저 배열의 뒤 부터 두개씩 비교하여 앞부분의 숫자가 더 큰 경우가 있는 인덱스를 찾는다.
37+ //없는 경우 -1를 출력하고 종료한다.
38+ int i = N - 1 ;
39+ while (i > 0 && num [i - 1 ] <= num [i ]) i --;
40+ if (i <= 0 ) return false ;
41+
42+ //i-1를 이후로 경계로 두어 배열의 뒤에서 부터 i-1과 비교하여 i-1보다 작은 값을 찾는다.
43+ //예 3 4 | 1 2 5 로 나뉘고 뒤부터 앞의 경계값인 4와 바교한다.
44+ int j = N - 1 ;
45+ while (j > 0 && num [i - 1 ] <= num [j ]) j --;
46+
47+ //i-1자리와 j를 스왑하여 위치 바꾼다.
48+ //예 3 2 1 2 5
49+ int tmp = num [i - 1 ];
50+ num [i - 1 ] = num [j ];
51+ num [j ] = tmp ;
52+
53+ //i-1 이후 i~N-1 자리까지 내림 차순으로 정렬 한다.
54+ // 3 2 | 1 4 5 => 3 2 5 4 1
55+ j = N - 1 ;
56+ while (i < j ) {
57+ tmp = num [i ];
58+ num [i ] = num [j ];
59+ num [j ] = tmp ;
60+ i += 1 ;
61+ j -= 1 ;
62+ }
2363
2464
65+ return true ;
2566 }
2667
27- // private static void perm(int[] visited, int[] find, int[] num, int n, int r, int count) {
28- // if(n==r){
29- // result.add(find.clone());
30- // int same=0;
31- // for (int i = 0; i < find.length; i++) {
32- // if(find[i]==num[i]){
33- // same+=1;
34- // }
35- // }
36- //
37- // if(same==n){
38- // sameIdx=step;
39- // if (sameIdx==0){
40- // System.out.println(-1);
41- // }else{
42- //
43- // int [] tmp = result.get((sameIdx-1));
44- // StringBuilder sb =new StringBuilder();
45- // for (int i = 0; i < tmp.length; i++) {
46- // sb.append(tmp[i]+" ");
47- // }
48- // System.out.println(sb.toString());
49- // }
50- // System.exit(0);
51- // }
52- // step+=1;
53- // return;
54- // }
55- // for (int i = 0; i < n; i++) {
56- // if(visited[i]==0){
57- // visited[i]=1;
58- // find[r]=i+1;
59- // perm(visited, find, num, n, r+1, count+1);
60- // visited[i]=0;
61- // }
62- //
63- // }
64- //}
68+
6569}
0 commit comments