See LCS again
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述
There are A, B two sequences, the number of elements in the sequence is n、m;
Each element in the sequence are different and less than 100000.
Calculate the length of the longest common subsequence of A and B.
输入
The input has multicases.Each test case consists of three lines;
The first line consist two integers n, m (1 < = n, m < = 100000);
The second line with n integers, expressed sequence A;
The third line with m integers, expressed sequence B;
输出
For each set of test cases, output the length of the longest common subsequence of A and B, in a single line.
样例输入
5 4
1 2 6 5 4
1 3 5 4
样例输出
3
普通做法根本连数组也开不到dp【100000】【100000】,但是这里也贴一下我的普通代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define max(a,b) a>b?a:b
int dp[10001][10001];
int a[100010],b[100010];
int n,m;
void LCS()
{
int j,k,i,t;
for (i=1;i<=n;++i)
{
for (j=1;j<=m;++j)
{
if(a[i]==b[j])
{
dp[i][j]=dp[i-1][j-1]+1;
continue;
}
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
int main()
{
int i;
while (~scanf("%d %d",&n,&m))
{
for (i=0;i<=n;++i)
{
dp[i][0]=0;
dp[0][i]=0;
}
for (i=1;i<=n;++i)
{
scanf("%d",&a[i]);
}
for (i=1;i<=m;++i)
{
scanf("%d",&b[i]);
}
LCS();
printf("%d\n",dp[n][m]);
}
return 0;
}
思路:
许多大牛的博客一开始就说用LCS转LIS,但为什么要找最长的递增序列呢?从例子可以看出,如1 2 6 5 4的数组里的编号为1,2,3,4,5;所以在第二个数列中找相同的就是1,4,5的编号了。问题就来了,如果1,3,5,4的数列变为1,3,4,5呢?那编号不就变了1,5,4。而看回原来的两个数列分别是1,2,6,5,4与1,3,4,5那一对比不就最长为2.因为它要求的是最长的公共序列,那正是编号要最长的递增啊!
#include <iostream>
#include <cstring>
using namespace std;
int a[100010],dp[100010];
int BS(int *p,int R,int t)
{
int L=0,mid;
while (L<R)
{
mid=(L+R)/2;
if (p[mid]<dp[t])
{
L=mid+1;
}
else
{
R=mid;//这里写了mid-1一直WA。。。
}
}
return L;
}
int main()
{
int i,j,k,n,m;
while (cin >> n >> m)
{
memset(a,0,sizeof(a));
for (i=1;i<=n;++i)
{
cin >> k;
a[k]=i;
}
for (i=1,j=0;i<=m;++i)
{
cin >> k;
if (a[k])
{
dp[j++]=a[k];
}
}
k=0;
a[k++]=dp[0];
for (i=1;i<j;++i)
{
if(a[k-1]<dp[i])
a[k++]=dp[i];
else
a[BS(a,k-1,i)]=dp[i];
}
cout << k << endl;
}
return 0;
}