您的位置:首页 > 其它

题意:给两个序列(长度达10^5,序列内的数都不同且都小于10^5),求这两个序列的最长公共序列的长度

2015-06-02 14:06 381 查看
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <map>
#define LL long long
#define N 100100
using namespace std;
int a
, b
, dp
;    //nyoj  See LCS again
/*
题意:给两个序列(长度达10^5,序列内的数都不同且都小于10^5),求这两个序列的最长公共序列的长度
解法:预处理,把相同的项记录其数组位置,将题目转化为求这个数组的最长单调递增序列的长度(用二分法优化)
*/
int binarysearch(int key, int len)
{
int l=0, r=len-1, mid;
while(l<=r)
{
mid=(l+r)>>1;
if(dp[mid]>key)
{
r=mid-1;
}
else if(dp[mid]<key)
{
l=mid+1;
}
else return mid;
}
return l;
}

int main()
{
int n, m, t, j, k, l;
while(scanf("%d%d", &n, &m)!=EOF)
{
memset(a, 0, sizeof(a));
for(t=1; t<=n; ++t)
{
scanf("%d", &k);
a[k]=t;
}
for(t=j=0; t<m; ++t)
{
scanf("%d", &k);
if(a[k])
{
b[j++]=a[k];
}
}
dp[0]=b[0];
for(t=l=1; t<j; ++t)
{
k=binarysearch(b[t], l);
dp[k]=b[t];
if(k+1>l)
l=k+1;
}
printf("%d\n", l);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: