Home BOJ. Longest Increasing Subsequence(4) (14002)
Post
Cancel

BOJ. Longest Increasing Subsequence(4) (14002)

[Link] https://www.acmicpc.net/problem/14002


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
55
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static int max = 0, maxIdx = 0;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;

		int n = toi(br.readLine());
		line = getLine();
		Info[] dp = new Info[n];
		int max = 0, maxIdx = 0;

		for(int i = 0; i < n; i++) {
			int v = toi(line[i]);
			dp[i] = new Info(v);

			for(int j = 0; j < i; j++) {
				if(v <= dp[j].val) continue;
				if(dp[i].step < dp[j].step + 1) {
					dp[i].step = dp[j].step + 1;
					dp[i].from = j;
				}
			}
			if(max < dp[i].step) {
				max = dp[i].step;
				maxIdx = i;
			}
		}
		Stack<Integer> stack = new Stack<>();
		while(true) {
			stack.push(dp[maxIdx].val);
			if(dp[maxIdx].from == -1) break;
			maxIdx = dp[maxIdx].from;
		}
		sb.append(max).append("\n");
		while(!stack.isEmpty()) sb.append(stack.pop()).append(" ");
		print(sb);
	}

	static class Info {
		int from = -1;
		int val;
		int step = 1;
		Info(int val) { this.val = val; }
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.