File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
weekly/week05/BOJ_14002_가장긴증가하는부분수열4 Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ package study .week05 ;
2+
3+ import java .io .BufferedReader ;
4+ import java .io .IOException ;
5+ import java .io .InputStreamReader ;
6+ import java .util .Arrays ;
7+ import java .util .Stack ;
8+
9+ // 가장 긴 증가하는 부분 수열4
10+ public class BOJ_14002 {
11+
12+ public static void main (String [] args ) throws IOException {
13+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
14+ StringBuilder sb = new StringBuilder ();
15+
16+ int N = Integer .parseInt (br .readLine ());
17+
18+ int [] arr = new int [N ];
19+ String []s = br .readLine ().split (" " );
20+
21+ for (int i =0 ; i <N ; i ++){
22+ arr [i ] = Integer .parseInt (s [i ]);
23+ }
24+
25+ int [] dp = new int [N ];
26+ int [] pre = new int [N ];
27+ Arrays .fill (dp , 1 );
28+ pre [0 ] = 0 ;
29+
30+ for (int i =1 ; i <N ; i ++){
31+ for (int j =0 ; j < i ; j ++){
32+ if (arr [i ] > arr [j ]){
33+ if (dp [i ] < dp [j ] + 1 ){
34+ dp [i ] = dp [j ] + 1 ;
35+ pre [i ] = j ;
36+ }
37+ }else {
38+ if (dp [i ] <= 1 ) {
39+ dp [i ] = 1 ;
40+ pre [i ] = i ;
41+ }
42+ }
43+ }
44+ }
45+
46+ int max = 0 ;
47+ int maxIdx = 0 ;
48+ for (int i =0 ; i <N ; i ++){
49+ if (max < dp [i ]){
50+ max = dp [i ];
51+ maxIdx = i ;
52+ }
53+ }
54+
55+ // 최대 부분수열 길이
56+ sb .append (max ).append ("\n " );
57+
58+ Stack <Integer > st = new Stack <>();
59+ st .push (arr [maxIdx ]);
60+ int tmp = maxIdx ;
61+
62+ while (true ){
63+ if (tmp == pre [tmp ])break ;
64+ tmp = pre [tmp ];
65+ st .push (arr [tmp ]);
66+ }
67+
68+ while (!st .isEmpty ()){
69+ sb .append (st .pop ()).append (" " );
70+ }
71+
72+ System .out .println (sb );
73+ }
74+ }
You can’t perform that action at this time.
0 commit comments