题目链接:https://www.luogu.com.cn/problem/P1439
首先这是一道绿题,如果用动态规划(时间复杂度n^2)对于n=10 ^5肯定过不了,当然动态规划适合leetcode这道题1143. 最长公共子序列感兴趣可以看看
题解如下:
/**
* 动态规划+内存优化
*/
public int longestCommonSubsequence(String text1, String text2) {
if (text1 == null || text2 == null) return 0;
if (text1.length() < text2.length()) {
longestCommonSubsequence2(text2, text1);
}
char chars1[] = text1.toCharArray(), chars2[] = text2.toCharArray();
int dp[] = new int[chars2.length + 1];
for (int i = 1; i <= chars1.length; i++) {
int cur = 0;
for (int j = 1; j <= chars2.length; j++) {
int leftTop = cur;
cur = dp[j];
if (chars1[i - 1] == chars2[j - 1]) {
dp[j] = leftTop + 1;
} else {
dp[j] = Math.max(dp[j], dp[j - 1]);
}
}
}
return dp[chars2.length];
}
言归正传,既然动态规划(时间复杂度n^2)解决不了这题,那我们得寻求另一种解法:
- 这题与leetcode那题有所不同,两组数据是n的全排序,所以说公共的数只是在两组数据的位置不同罢了,而最长公共子序列的数的索引必然是递增的!
- 把两组数据转化成,第二组数据在第一组数据出现的位置,并按顺序保留索引,故而将原问题的解转换成对当前索引求其最长上升子序列(严格递增)类似问题的(最长不下降序列)(nlogn解法)的问题
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int map[] = new int[n + 1];
int top[] = new int[map.length];
for (int i = 0; i < n; i++) {
map[in.nextInt()] = i;
}
int len = 1;
top[0] = map[in.nextInt()];
for (int i = 1; i < n; i++) {
int nowIndex = map[in.nextInt()];
if (nowIndex > top[len - 1]) {
top[len++] = nowIndex;
continue;
}
int begin = 0, end = len;
while (begin < end) {
int mid = (begin + end) >> 1;
if (nowIndex <= top[mid]) {//找到第一个大于等于nowIndex的索引
end = mid;
} else {
begin = mid + 1;
}
}
top[begin] = nowIndex;
}
System.out.println(len);
}
}