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

POJ 1458 Common Subsequence (动规,最长公共子序列)

2014-05-20 16:07 399 查看


Problem A


Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)


Total Submission(s) : 33 Accepted Submission(s) : 18


Problem Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = another sequence Z = is a subsequence of X if there exists a strictly increasing sequence of indices of X such that for all j = 1,2,...,k,
xij = zj. For example, Z = is a subsequence of X = 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. The program input
is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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




Statistic | Submit | Back

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAXN=1000+5;
int lcs[MAXN][MAXN];

int main()
{
	//freopen("123.txt","r",stdin);
	int i,j,k;
	char s1[MAXN],s2[MAXN];
	while(~scanf("%s",s1))
	{
		scanf("%s",s2);
		memset(lcs,0,sizeof(lcs));
		int len1=strlen(s1);
		int len2=strlen(s2);
		for(i=1;i<=len1;i++)
			for(j=1;j<=len2;j++)
				if(s1[i-1]==s2[j-1])lcs[i][j]=lcs[i-1][j-1]+1;
				else if(lcs[i-1][j]>lcs[i][j-1])lcs[i][j]=lcs[i-1][j];
				else lcs[i][j]=lcs[i][j-1];
		printf("%d\n",lcs[len1][len2]);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: