[luogu] P1439 【模板】最长公共子序列

[luogu] P1439 【模板】最长公共子序列

题目详情
题目分析:这个题目用到了离散化的思想,实在太妙了!
本题样例:
序列A:3 2 1 4 5
序列B:1 2 3 4 5
我们注意到序列A是乱序的,但我们可以强行顺序化。
为什么能强行顺序化呢?
因为题目里提供的序列都是全排列。所以从1~n每个数都有一个。我们把序列A中的每个元素分别映射为12345,这样序列B按照对应的映射规则变成32145,所以只要求序列B的最长上升子序列就是两个序列的最长公共子序列。

#include <cstdio>
#include <algorithm>
using namespace std;
int n, a[111111], b[111111], map[111111], top, LCS[111111];
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++){
        scanf("%d", a + i);
        map[a[i]] = i;//把a[i]按顺序映射成i
    }
    for (int i = 1; i <= n; i++)
        scanf("%d", b + i);
    for (int i = 1; i <= n; i++){
        if (map[b[i]] > LCS[top])//用同样的映射关系把b[i],映射成对应数字。
            LCS[++top] = map[b[i]];
        else
            *lower_bound(LCS + 1, LCS + top + 1, map[b[i]]) = map[b[i]];//STL中的二分查找。
    }
    printf("%d\n", top);
    return 0;
}
发布了7 篇原创文章 · 获赞 0 · 访问量 65

猜你喜欢

转载自blog.csdn.net/weixin_45646006/article/details/105105757