Common Subsequence
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 44093 Accepted: 18026
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
这是最长公共子序列问题(LCS)。
str1、str2分别表示输入的两个字符串。
二维DP数组dp[i][j]表示以str1[i],str2[j]为止,它们的最长公共子序列长度。
对于dp[i][j],如果str1[i]==str2[j],那么当前最长公共子序列长度应该是不考虑str1[i]、str2[j]的情况下加一,即dp[i][j]=dp[i-1][j-1]+1。
如果str1[i]!=str2[j],那么当前最长公共子序列长度应该是不考虑str1[i]或者不考虑str2[j]的情况下的LCS长度的较大者,即dp[i][j]=max(dp[i-1][j],dp[i][j-1])。
//
// main.cpp
// 基础DP1-L-Common Subsequence
//
// Created by 袁子涵 on 15/10/24.
// Copyright © 2015年 袁子涵. All rights reserved.
//
// 0ms 924KB
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
char str1[201],str2[201];
int dp[201][201],out;
bool visit[201][201];
int DP(int a,int b)
{
if (visit[a][b] || a==0 || b==0) {
return dp[a][b];
}
if (str1[a-1]==str2[b-1]) {
dp[a][b]=DP(a-1,b-1)+1;
}
else
dp[a][b]=max(DP(a-1,b),DP(a,b-1));
visit[a][b]=1;
return dp[a][b];
}
int main(int argc, const char * argv[]) {
while (scanf("%s%s",str1,str2)!=EOF) {
dp[0][0]=0;
memset(visit, 0, sizeof(visit));
out=DP((int)strlen(str1),(int)strlen(str2));
cout << out << endl;
}
return 0;
}