天天看点

UVA - 10635 Prince and Princess LCS转LIS

题目链接:

http://bak.vjudge.net/problem/UVA-10635

Prince and Princess

Time Limit: 3000MS

题意

给你两个数组,求他们的最长公共子串。

题解

每个数组的大小最大有62500,所以n^2的经典算法肯定行不通。

那么,我么就需要找突破口:这题和一般的最长公共子串问题有什么不同,题目告诉我们每个数字只出现一次。明显要在这上面做文章!由于每个数位子固定了,所以匹配是唯一的,(pos1,pos2)表示数x在a数组中的位置,在b数组中的位置。我们按顺序处理出所有的这样的顶点对。然后题目就转换成了二维的最长上升子串问题了。

代码

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<vector>
#include<cstdio>
#include<string>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#include<sstream>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
#define scf scanf
#define prf printf

typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;

const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;
const double PI = acos(-1.0);

//start----------------------------------------------------------------------

const int maxn=255*255;

int mp[maxn];
int a[maxn],b[maxn];

int arr[maxn];

int main() {
    int tc,kase=0;
    int n,p,q;
    scf("%d",&tc);
    while(tc--){
        scf("%d%d%d",&n,&p,&q);
        p++,q++;
        clr(mp,-1);
        for(int i=1;i<=p;i++) scf("%d",&a[i]);
        for(int i=1;i<=q;i++){
            scf("%d",&b[i]);
            mp[b[i]]=i;
        }

        int tot=0;
        for(int i=1;i<=p;i++){
            if(mp[a[i]]>=0){
                arr[++tot]=mp[a[i]];
            }
        }

//        for(int i=1;i<=tot;i++) prf("%d\n",arr[i]);

        vector<int> ra;
        for(int i=1;i<=tot;i++){
            int pos=upper_bound(all(ra),arr[i])-ra.begin();
            if(pos==ra.sz()){
                ra.pb(arr[i]);
            }else{
                ra[pos]=arr[i];
            }
        }
        prf("Case %d: %d\n",++kase,ra.sz());
    }
    return 0;
}

//end-----------------------------------------------------------------------