洛谷P1439(长度相同下LCS转LIS做法)

题目描述

给出1-n的两个排列P1和P2,求它们的最长公共子序列。

输入输出格式

输入格式:

第一行是一个数n,

接下来两行,每行为n个数,为自然数1-n的一个排列。

输出格式:

一个数,即最长公共子序列的长度

输入输出样例

输入样例#1: 复制

5 
3 2 1 4 5
1 2 3 4 5

输出样例#1: 复制

3

说明

【数据规模】

对于50%的数据,n≤1000

对于100%的数据,n≤100000

一看数据  n^2 肯定是蒙蔽的  过不去  必须降低复杂度

这里我们用到一种离散化的思想  即

将第一组数据与它的位置对应上

比如  3-1, 2-2, 1-3,4-4,5-5

每个数字的位置都是上升的, 然后我们根据第二个序列,  从头开始判断 第二个序列的每一个数字在离散化处理好的数组中

的位置,强制使它有序,就转化成了  nlongn复杂度求LIS的问题  

关于 nlongn复杂度求LIS  可以看我的另一篇博客https://blog.csdn.net/Soul_97/article/details/81282710

#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const int inf = 0x3f3f3f3f;
int n;
int a[N],b[N],f[N];
int main()
{
    ios::sync_with_stdio(false);

    cin >> n;

    int t;
    for(int i = 1;i <= n;i ++)
        cin >> t, a[t] = i;

    for(int i = 1;i <= n;i ++)
        cin >> b[i];

    memset(f,inf,sizeof(f));

    for(int i = 1;i <= n;i ++)
    {
        int pos = lower_bound(f,f + n + 1,a[b[i]]) - f;

        f[pos] = a[b[i]];
    }

    int len = 0;
    for(int i = 0;i <= n;i ++)
        if(f[i] != inf) len ++;
    cout << len << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Soul_97/article/details/81454211