http://ayit.acmclub.com/index.php?app=problem_title&id=233&problem_id=21813
最长公共子序列的题目,但是这道题目的数据量太大,直接用dp 会超时,只能另想办法。
首先找到 B 串中各个元素在 A 串中对应的位子,构成一个序列,然后求这个序列的最长单调递增子序列 的长度即可。
在查找 B串中元素在 A 串中的位子的时候不能直接暴力搜索,要用到 二分法,也可以用 lower_bound() ,这两种方法都要求待查序列式有序的,所以要对 A 串进行排序,但是如果是正常的排序,排序后 A 串中元素的位子就改变了。 所以要用到结构体,或者用 两个数组,一个保存元素,一个保存位子,这里我用的是结构体。
但是对结构体进行排序很简单,要用 lower_bound(), 对结构体中的元素进行查找就不好弄了。这有涉及到另外一个知识点,操作符重载(我最薄弱的一点。。)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int inf = 0x7fffffff;
int s[100010],t[100010],b[100010], dp[100010];
struct A
{
int x, y;
A(int xx,int yy): x(xx),y(yy){}
A(){}
bool operator < (const A & n)const
{
return x < n.x;
}
}a[100010];
int cmp (A p1, A p2)
{
return p1.x< p2.x;
}
int getlen(int n)
{
int top = 0,i,j;
int Stack[100010] = {-inf};
for(i = 0; i < n; i++)
{
if(dp[i] > Stack[top]) Stack[++top] = dp[i];
else
{
int id = lower_bound(Stack,Stack + top,dp[i]) - Stack;
Stack[id] = dp[i];
}
}
return top;
}
int main()
{
int n,m,i,j;
while(cin>>n>>m)
{
memset(a,0,sizeof(a));
memset(dp,0,sizeof(dp));
for(i = 0; i < n; i++)
cin>>a[i].x, a[i].y = i;
sort(a,a + n, cmp);
for(i = 0; i < m; i++)
{
cin>>b[i];
int p = lower_bound(a,a+n,A(b[i],0)) - a;
if(p < n && b[i] == a[p].x) dp[j++] = a[p].y;
}
cout<<getlen(j)<<endl;
}
return 0;
}