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

POJ-1458-Common Subsequence-经典DP

2017-11-19 11:54 417 查看
题目来源:http://poj.org/problem?id=1458

Common Subsequence

Time Limit: 1000MS Memory Limit: 10000K

Total Submissions: 55804 Accepted: 23228

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

题目介绍:在串X和串Y中找出最长公共子串,公共子串这个定义这里就不阐述了,直接讲方法。

我们定义dp[i][j]为串X从下标为0到i,与串Y从下标为0到j所形成的最长公共子串,即最优子结构。注意,为什么不是下标从1到i?因为这里采用直接输入字符串的方式,所以下标是从0开始的,为什么是到i,j而不是到i-1,j-1?因为我们DP要考虑的是下一个状态,所以最后的一个状态是i-1和j-1的下一个状态,即dp[lenX][lenY]为最后结果。

状态转移方程:

1):当str1[i] == str2[j]的时候,即X,Y分别检测到i,j这个位置的时候,两串在相应的位置相等,那么显然有dp[i+1][j+1] = dp[i][j]+1;

2):当str1[i] != str2[j]的时候,即X,Y分别检测到i,j这个位置的时候,两串在相应的位置不相等,那么下一个状态的最优解dp[i+1][j+1]就应该要在dp[i][j+1]和dp[i+1][j]里面选,从语言上表达就是分别把X,Y往之前挪一个位置,看看这两个状态哪一个更优,这里要注意,为什么前一个状态有dp[i+1][j],dp[i][j+1],就是没有dp[i][j]?因为这一个状态是另外两个状态的子结构,所以当考虑到dp[i+1][j]或者dp[i][j+1]的时候,必然已经经历过dp[i][j]这一个状态了。分析到此为止。

AC代码:

#include<iostream>
#include<string.h>
using namespace std;

char str1[10005];
char str2[10005];
int main(){

while(cin >> str1 >> str2){

int dp[1005][1005] ={0};
int len1 = strlen(str1);
int len2 = strlen(str2);

for(int i = 0 ; i <len1;i++){
for(int j = 0; j < len2 ; j ++){
if(str1[i] == str2[j]){
dp[i+1][j+1] = dp[i][j]+1;
}else{
dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
}
}
}
cout << dp[len1][len2]<<endl;
}

}


这里要注意,这题是到经典题,但是有些地方的取值范围还是不一样的,所以数组有可能存在开的过小的情况,不在外部定义主要的一点是有循环输入的存在,为了避免每一次都初始化的麻烦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: