-
Notifications
You must be signed in to change notification settings - Fork 7
/
2127 Greatest Common Increasing Subsequence.java
67 lines (66 loc) · 1.57 KB
/
2127 Greatest Common Increasing Subsequence.java
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
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
private static int flag = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length1 = in.nextInt();
int[] input1 = new int[length1 + 1];
for (int i = 1; i <= length1; ++i) {
input1[i] = in.nextInt();
}
int length2 = in.nextInt();
int[] input2 = new int[length2 + 1];
for (int i = 1; i <= length2; ++i) {
input2[i] = in.nextInt();
}
int[][] dp = new int[length1 + 1][length2 + 1];
int[][] path = new int[length1 + 1][length2 + 1];
for (int i = 1; i <= length1; ++i) {
int max = 0;
int maxVal = 0;
for (int j = 1; j <= length2; ++j) {
if (dp[i][j] < dp[i - 1][j]) {
dp[i][j] = dp[i - 1][j];
path[i][j] = j;
}
if (input1[i] == input2[j]) {
if (dp[i][j] < max + 1) {
dp[i][j] = max + 1;
path[i][j] = maxVal;
}
}
if (input2[j] < input1[i]) {
if (max < dp[i - 1][j]) {
max = dp[i - 1][j];
maxVal = j;
}
}
}
}
int rst = 1;
for (int i = 1; i <= length2; ++i) {
if (dp[length1][rst] < dp[length1][i]) {
rst = i;
}
}
System.out.println(dp[length1][rst]);
output(path, dp, input1, input2, length1, rst);
System.out.println("");
}
private static void output(int[][] path, int[][] dp, int[] input1, int[] input2, int x, int y) {
if (x == 0) {
return;
}
output(path, dp, input1, input2, x - 1, path[x][y]);
if (path[x][y] != y) {
if (flag == 1) {
System.out.print(" ");
} else {
flag = 1;
}
System.out.print(input2[y]);
}
}
}