NYoj--760(动规,LCS转LIS)

2014-08-31 13:40:13

See LCS again

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
 
描述

There are A, B two sequences, the number of elements in the sequence is n、m;

Each element in the sequence are different and less than 100000.

Calculate the length of the longest common subsequence of A and B.

 
输入
The input has multicases.Each test case consists of three lines;
The first line consist two integers n, m (1 < = n, m < = 100000);
The second line with n integers, expressed sequence A;
The third line with m integers, expressed sequence B;
输出
For each set of test cases, output the length of the longest common subsequence of A and B, in a single line.
样例输入
5 4
1 2 6 5 4
1 3 5 4
样例输出
3

思路:DP好题,如果直接LCS递推求解的话,时间复杂度是O(n^2),接受不了。所以这样处理:先记录串A中每个数的位置,再在读入串B时记录串B中每个数在串A中的位置pos,然后就是在pos数组中求LIS的问题了,用经典的二分优化LIS,O(nlogn)的复杂度。
 1 /*************************************************************************
 2     > File Name: ny760.cpp
 3     > Author: Nature
 4     > Mail: 564374850@qq.com 
 5     > Created Time: Sun 31 Aug 2014 12:46:14 PM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <cmath>
12 #include <iostream>
13 #include <algorithm>
14 using namespace std;
15 
16 int v1,v2;
17 int p1[100005];
18 int pos[100005];
19 int que[100005];
20 int n,m;
21 int len;
22 
23 int B_search(int val){
24     int l = 1,r = len + 1,mid;
25     while(l < r){
26         mid = l + (r - l) / 2;
27         if(que[mid] < val)
28             l = mid + 1;
29         else
30             r = mid;
31     }
32     return l;
33 }
34 
35 int main(){
36     while(scanf("%d%d",&n,&m) == 2){
37         memset(p1,0,sizeof(p1));
38         memset(pos,0,sizeof(pos));
39         for(int i = 1; i <= n; ++i){
40             scanf("%d",&v1);
41             p1[v1] = i;
42         }
43         for(int i = 1; i <= m; ++i){
44             scanf("%d",&v2);
45             pos[i] = p1[v2];
46         }
47         len = 0;
48         for(int i = 1; i <= m; ++i){
49             if(pos[i] == 0) continue;
50             int index = B_search(pos[i]);
51             que[index] = pos[i];
52             if(index > len)
53                 ++len;
54             //printf("plus:%d , len:%d\n",pos[i],len);
55         }
56         printf("%d\n",len);
57     }
58     return 0;
59 }

 

posted @ 2014-08-31 13:43  Naturain  阅读(187)  评论(0编辑  收藏  举报