UVa 10635 Prince and Princess(LCS N*logN)

题意:

给定两个序列,求两个序列的最长公共子序列。

思路:

http://www.cnblogs.com/kedebug/archive/2012/11/16/2774113.html

前面有篇文章写过了关于LIS N*logN的算法,具体就不多说了。

这题是关于LCS的,咋一看,很简单,结果轻松超时了。因为题目数据是(250*250)^2,O(n^2)的LCS肯定是会超时的。

关于LCS的N*logN算法,主要是借鉴了http://www.cnblogs.com/staginner/archive/2011/12/04/2275571.html

引用其文章中说的:

比如现在我们要找A、B的最长公共子序列,其中
A:1 3 9 2 3
B:3 2 1 7 2 3
我们要在A中找到B中的各个字符出现的位置,
3:2 5
2:4
1:1
7:没有
2:4
3:2 5
然后依次把右边的数写出来,但是对于每个“:”后面的一组数要逆序输出,因为在B中那个位置只有一个元素,所以要避免在做最长上升子序列的时候在那一个位置选择了多于一个的元素。
这样我们就得到了5 2 4 1 4 5 2,对这个序列求最长上升子序列即可。

由于本题中,每个元素在序列中只出现过一次,所以只需要简单的hash便可以应付。

#include <cstdio>
#include <cstdlib>
#include <cstring>

const int MAXN = 65600;
int n, p, q;
int stack[MAXN], hash[MAXN];

int main()
{
    int cases, t = 0;
    scanf("%d", &cases);
    while (cases--)
    {
        scanf("%d %d %d", &n, &p, &q);
        ++p, ++q;

        memset(hash, 0, sizeof(hash));

        for (int i = 1; i <= p; ++i)
        {
            int v;
            scanf("%d", &v);
            hash[v] = i;
        }

        int top = 0;
        stack[top] = -1;

        for (int i = 1; i <= q; ++i)
        {
            int v;
            scanf("%d", &v);
            v = hash[v];
            if (v)
            {
                if (v > stack[top])
                    stack[++top] = v;
                else
                {
                    int l = 1, r = top;
                    while (l <= r)
                    {
                        int mid = (l + r) >> 1;
                        if (stack[mid] < v)
                            l = mid + 1;
                        else
                            r = mid - 1;
                    }
                    stack[l] = v;
                }
            }
        }
        printf("Case %d: %d\n", ++t, top);
    }
    return 0;
}
-------------------------------------------------------

kedebug

Department of Computer Science and Engineering,

Shanghai Jiao Tong University

E-mail: kedebug0@gmail.com

GitHub: http://github.com/kedebug

-------------------------------------------------------

原文地址:https://www.cnblogs.com/kedebug/p/2783228.html