nyoj 760 See LCS again 最长公共子序列

正常dp的最长公共子序列时间复杂度为n*m;
优化后的为nlogn~n*m*log(nm),不是太稳定,不过做这道题时还是可以A的,毕竟数字不是字母,相同的还是很少的;
思路:
如:
5 7
1 2 6 5 4
1 3 2 4 6 6 5
先查找第一个子串在第二个中出现的下标如1(1),2(3) ,6(6,5),5(7),4(4);(注意:下标逆序排列)
然后构成一个新的子串1,3,6,5,7,4;
直接求最长递增子序列就好了,即4。
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
代码:

#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
int a[100010],b[100010],c[1000010],dp[1000010];
int binary(int num,int &maxx)  //最长单调递增子序列
{
    int i,mid,l=1,r=maxx;
    while(l<=r)
    {
        mid=(l+r)>>1;
        if(dp[mid]>num)
            r=mid-1;
        else if(dp[mid]<num)
            l=mid+1;
        else
        {
            l=mid;
            break;
        }
    }
    dp[l]=num;
    if(l>maxx)
        maxx++;
}
int main()
{
    int n,m;
    vector<int>v[50001];  //假设b[]中出现的数字最大为50000
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int i,j,k=0;
        for(i=1; i<=50000; i++)
            v[i].clear();  //vector清空
        for(i=1; i<=n; i++)
            scanf("%d",&a[i]);
        for(i=1; i<=m; i++)
            scanf("%d",&b[i]);
        for(i=m; i>=1; i--)
            v[b[i]].push_back(i);  //逆序求下标存在vector中
        for(i=1; i<=n; i++)
            for(j=0; j<v[a[i]].size(); j++)
                c[++k]=v[a[i]][j];  //构成新的子串存在c[]中
            dp[1]=c[1];
        int maxx=1;
        for(i=2; i<=k; i++)
            binary(c[i],maxx);  //求最长单调递增子序列
        printf("%d\n",maxx);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值