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

<Sicily> Longest Common Subsequence

2016-06-16 09:51 417 查看

一、题目描述

Given a sequence A = < a1, a2, …, am >, let sequence B = < b1, b2, …, bk > be a subsequence of A if there exists a strictly increasing sequence ( i1 < i2 < i3 …, ik ) of indices of A such that for all j = 1,2,…,k, aij = bj. For example, B = < a, b, c, d > is a subsequence of A= < a, b, c, f, d, c > with index sequence < 1, 2, 3 ,5 >。

Given two sequences X and Y, you need to find the length of the longest common subsequence of X and Y.

二、输入

The input may contain several test cases.

The first line of each test case contains two integers N (the length of X) and M(the length of Y), The second line contains the sequence X, the third line contains the sequence Y, X and Y will be composed only from lowercase letters. (1<=N, M<=100)

Input is terminated by EOF.

三、输出

Output the length of the longest common subsequence of X and Y on a single line for each test case.

例如:

输入:

6 4

abcfdc

abcd

2 2

ab

cd

输出:

4

0

四、解题思路

这道题需要求的是最长公共子序列,典型的动态规划问题。

设序列1:X = < x1, x2, x3, …, xm>,子序列2:Y=< y1, y2, y3,…yn>。假如他们的最长公共子序列为Z=< z1, z2, z3,…zk>那么k就是我们需要求的长度。

由上面假设可以推出:

1)如果xm=yn,那么必有xm=yn=zk,且< x1,x2,x3,…xm-1>与< y1,y2,y3,…yn-1>的最长公共子序列为< z1, z2, z3,…zk-1>

2)如果xm!=zk,那么< z1, z2, z3,…zk>是< x1,x2,x3,…xm-1>与< y1, y2, y3,…yn>的最长公共子序列。

3)如果yn!=zk,那么< z1, z2, z3,…zk>是< x1,x2,x3,…xm>与< y1, y2, y3,…yn-1>的最长公共子序列。

由此可以逆推。于是有以下公式:



五、代码

#include<iostream>
#include<math.h>

using namespace std;

int main()
{
int strALeng, strBLeng;
while(cin >> strALeng >> strBLeng)
{
int charMatrix[101][101];

char charAAry[strALeng];
char charBAry[strBLeng];

for(int i = 0; i < strALeng; i++)
cin >> charAAry[i];

for(int i = 0; i < strBLeng; i++)
cin >> charBAry[i];

for(int i = 0; i < strALeng; i++)
charMatrix[i][0] = 0;

for(int i = 0; i < strBLeng; i++)
charMatrix[0][i] = 0;

for(int i = 1; i <= strALeng; i++)
{
for(int j = 1; j <= strBLeng; j++)
{
if(charAAry[i - 1] == charBAry[j - 1]) charMatrix[i][j] = charMatrix[i - 1][j - 1] + 1;
else charMatrix[i][j] = max(charMatrix[i][j-1], charMatrix[i - 1][j]);
}
}

cout << charMatrix[strALeng][strBLeng] << endl;

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: