码迷,mamicode.com
首页 > 其他好文 > 详细

UVA - 10635 —— Prince and Princess

时间:2016-03-19 19:39:06      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19051

首先,这题一看就知道是——最长公共子序列(LCS)

但是,会发现这道题的字符串长度可能达到62500,我们现在会的LCS的解法时间复杂度为O(n^2),所以是会超时的。

那么,这时候就要想:题目有没有给出更多的条件给我们,让我们能够在更快地时间内完成任务呢?

还真有!题目有一个反复强调的条件,就是:一个字符串的全部字符都是不同的!

所以,我们可以这样:

(1).将第一个字符串的每一个字符一一映射到1~n

(2).对于第二个字符串的每一个字符,

  ①若该字符在第一个字符串中出现过,那么就将该字符转化为它在(1)中所映射的字符;

  ②否则,就将该字符删去

这样,我们就得到了新的两个字符串,第一个字符串为1~n,第二个字符串完全由1~n内的字符构成,但是顺序却不是升序的。

这个时候,我们会发现一个很奇妙的事情:

  这时,两个字符串的LCS其实就是第二个字符串的LIS!

于是,一个LCS问题,因为字符串的字符均不同这一条件,被转化为一个LIS问题,而LIS问题可以有O(nlgn)时间复杂度的算法!

#include <cstdio>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;

const int MAXN = 62505;
int a[MAXN], c[MAXN];

int LIS(int *a, int len)
{
    for(int i=0; i<len; i++)    c[i] = MAXN;
    
    for(int i=0; i<len; i++) {
        *lower_bound(c, c+len, a[i]) = a[i];
    }
    return lower_bound(c, c+len, MAXN) - c;
}

int main ()
{
    int t, n, P, Q, q, x;
    scanf("%d", &t);
    for(int kase=1; kase<=t; kase++) {
        scanf("%d%d%d", &n, &P, &q);
        map<int, int> mp;
        for(int i=0; i<P+1; i++) {
            scanf("%d", &x);
            mp[x] = i;
        }
        Q = 0;
        for(int i=0; i<q+1; i++) {
            scanf("%d", &x);
            if(mp.find(x) != mp.end()) {
                a[Q++] = mp[x];
            }
        }
        printf("Case %d: %d\n", kase, LIS(a, Q));
    }

    return 0;
}

 

UVA - 10635 —— Prince and Princess

标签:

原文地址:http://www.cnblogs.com/AcIsFun/p/5295858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!