|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + static StringTokenizer st; |
| 9 | + static int N; |
| 10 | + static int[] arr; |
| 11 | + static List<Integer> LIS; |
| 12 | + static int[] lisLen; |
| 13 | + static int[] realIdx; |
| 14 | + |
| 15 | + public static void main(String[] args) throws IOException { |
| 16 | + N = Integer.parseInt(br.readLine()); |
| 17 | + arr = new int[N+1]; |
| 18 | + LIS = new ArrayList<>(); |
| 19 | + lisLen = new int[N+1]; |
| 20 | + realIdx = new int[N+1]; |
| 21 | + |
| 22 | + st = new StringTokenizer(br.readLine()); |
| 23 | + for (int i = 1; i <= N; i++) { |
| 24 | + int cur = Integer.parseInt(st.nextToken()); |
| 25 | + arr[i] = cur; |
| 26 | + |
| 27 | + if(LIS.isEmpty() || LIS.get(LIS.size()-1) < cur){ |
| 28 | + LIS.add(cur); |
| 29 | + lisLen[i] = LIS.size();//맨 뒤에 붙이는 경우는 LIS길이만큼 만들 수 있는거 |
| 30 | + realIdx[LIS.size()-1] = i; |
| 31 | + } else { |
| 32 | + int pos = binarySearch(cur); |
| 33 | + LIS.set(pos, cur); |
| 34 | + lisLen[i] = pos + 1; //LIS는 0-base니까 1더해줌. 이진 탐색으로 찾은 위치까지 LIS를 만들 수 있다는 의미. |
| 35 | + realIdx[pos] = i; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + bw.write(LIS.size() + "\n"); |
| 40 | + |
| 41 | + List<Integer> result = new ArrayList<>(); |
| 42 | + int targetLength = LIS.size(); |
| 43 | + |
| 44 | + for (int i = N; i >= 1; i--) { |
| 45 | + if (lisLen[i] == targetLength) { |
| 46 | + result.add(arr[i]); |
| 47 | + targetLength--; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + Collections.reverse(result); |
| 52 | + |
| 53 | + for (int i : result) { |
| 54 | + bw.write(i + " "); |
| 55 | + } |
| 56 | + bw.write("\n"); |
| 57 | + |
| 58 | + bw.close(); |
| 59 | + } |
| 60 | + |
| 61 | + public static int binarySearch(int target) { |
| 62 | + int left = 0; int right = LIS.size() - 1; |
| 63 | + |
| 64 | + while(left < right){ |
| 65 | + int mid = (left + right) / 2; |
| 66 | + if(LIS.get(mid) < target){ |
| 67 | + left = mid + 1; |
| 68 | + } else { |
| 69 | + right = mid; |
| 70 | + } |
| 71 | + } |
| 72 | + return left; |
| 73 | + } |
| 74 | +} |
| 75 | +``` |
0 commit comments