题目大意:给出一串的数字要求求出他们的最长公共子序列
解题思路:本题的数据量颇大,用O(N^2)的算法肯定是不行的,所以要将最长公共子序列问题转换成求最长的递增子序列,为什么可以这么转,在百度上输入 最长公共子序列的nlogn算法,就会有一大堆的解释了,在这里就不解释了,这里的话,有一个点要注意,因为数字不重复,所以可以将第一行的数字转换成另一种形式,即1 7 5 4 8 3 9可以另一个种方法表示,即想将c数组设为0,然后c[1] = 1,c[7] = 2,c[5] = 3,c[4] = 4...以此类推。为什么可以这样表示,因为数字不重复, 这样转换的话,就变成了O(N)了,具体请看代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 260*260
int num1[maxn],num2[maxn],c1[maxn],c2[maxn],end[maxn],n,p,q;
void upbound(int v,int n) {
int first = 0;
while(first < v) {
int m = first + (v - first) / 2;
if(end[m] > n)
v = m;
else
first = m + 1;
}
end[first] = n;
}
int main() {
int test;
int mark = 1;
scanf("%d", &test);
while(test--) {
scanf("%d%d%d",&n,&p,&q);
memset(c1,0,sizeof(c1));
memset(c2,0,sizeof(c2));
for(int i = 1; i <= p+1; i++)
scanf("%d", &num1[i]);
for(int i = 1; i <= q+1; i++)
scanf("%d",&num2[i]);
for(int i = 1; i <= p+1; i++)
c1[num1[i]] = i;
int count = 1;
for(int i = 1; i <= q+1; i++) {
if(!c1[num2[i]])
continue;
else
c2[count++] = c1[num2[i]];
}
int top = 0;
end[top] = 0;
int len,max = -1;
for(int i = 1; i < count; i++) {
if(c2[i] == end[top]) {
len = top;
}else if(c2[i] > end[top]) {
end[++top] = c2[i];
len = top;
}else
upbound(top,c2[i]);
if(max < len)
max = len;
}
printf("Case %d: %d\n",mark++,max);
}
return 0;
}