https://www.acmicpc.net/problem/14002
11053번 문제에서, dp값을 역추적하는 문제
11053: https://velog.io/@mong7399/java-11053번-가장-긴-증가하는-부분-수열
import java.io.*;
import java.util.*;
public class Main {
static int N;
static int[] arr;
static int[] dp;
static int MaxResult = 1;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N];
dp = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0;i<N;i++){
arr[i] = Integer.parseInt(st.nextToken());
}
dp[0] = 1;
for(int i=1;i<N;i++){
dp[i] = 1;
for(int j=0;j<i;j++){
if(arr[j]<arr[i]){
dp[i] = Math.max(dp[j]+1,dp[i]);
MaxResult = Math.max(dp[i], MaxResult);
}
}
}
// 역추적 시작
int value = MaxResult;
Stack<Integer> stack = new Stack<>();
for(int i=N-1;i>=0;i--){
if(value == dp[i]){
stack.push(arr[i]);
value --;
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop() + " ");
}
System.out.println(MaxResult);
System.out.println(sb);
}
}