您的位置:首页 > 产品设计 > UI/UE

HDU 1159 & POJ 1458 Common Subsequence(LCS 最长公共子序列O(nlogn))

2015-10-03 10:09 483 查看
题目链接:

HDU : 1159 http://acm.hdu.edu.cn/showproblem.php?pid=1159

POJ :  1458http://poj.org/problem?id=1458

Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1,
i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find
the length of the maximum-length common subsequence of X and Y.
Input

The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output

For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample Input
abcfbc         abfcab
programming    contest
abcd           mnp

Sample Output
4
2
0

Source

Southeastern Europe 2003

模板来自:

http://karsbin.blog.51cto.com/1156716/966387

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1507;
vector<int> location[26];
int c[maxn*maxn] , d[maxn*maxn];

//nlogn 求lcs
int lcs(char a[],char b[])
{
int i , j , k , w , ans , l , r , mid ;
for( i = 0 ; i < 26 ; i++) location[i].clear() ;
for( i = strlen(b)-1 ; i >= 0 ; i--) location[b[i]-'a'].push_back(i) ;
for( i = k = 0 ; a[i]; i++)
{
for( j = 0 ; j < location[w=a[i]-'a'].size() ; j++,k++) c[k] = location[w][j] ;
}
d[1] = c[0] ;
d[0] = -1 ;
for( i = ans = 0 ; i < k ; i++)
{
l = 0 ;
r = ans ;
while( l <= r )
{
mid = ( l + r ) >> 1 ;
if( d[mid] >= c[i] ) r = mid - 1 ;
else l = mid + 1 ;
}
if( r == ans ) ans++,d[r+1] = c[i] ;
else if( d[r+1] > c[i] ) d[r+1] = c[i] ;
}
return ans ;
}

int main()
{
char a[maxn], b[maxn];
while(~scanf("%s%s",a,b))
{
printf("%d\n",lcs(a,b));
}
}


还有个O(n*n)的解法 + 滚动数组!

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 1000+10;
int dp[2][maxn];
char s1[maxn], s2[maxn];

void LCS(int len1, int len2)
{
for(int i = 1; i <= len1; i++)
{
for(int j = 1; j <= len2; j++)
{
if(s1[i-1] == s2[j-1])
dp[i%2][j] = dp[(i-1)%2][j-1]+1;
else
{
dp[i%2][j] = max(dp[(i-1)%2][j], dp[i%2][j-1]);
}
}
}
}

int main()
{
while(scanf("%s%s",s1,s2) != EOF)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
memset(dp,0,sizeof(dp));
LCS(len1, len2);
printf("%d\n", dp[len1%2][len2]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: