Problem B
Time Limit : 2000/1000ms (Java/Other) Memory Limit :65536/32768K (Java/Other)
Total Submission(s) : 1 Accepted Submission(s) : 1
Problem Description
A subsequence of a givensequence 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 strictlyincreasing sequence <i1, i2, ..., ik> of indices of X such thatfor all j = 1,2,...,k, xij = zj. For example, Z = <a, b, f, c> isa 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 findthe length of the maximum-length common subsequence of X and Y. <br>Theprogram input is from a text file. Each data set in the file contains twostrings representing the given sequences. The sequences are separated by anynumber of white spaces. The input data are correct. For each set of data theprogram prints on the standard output the length of the maximum-length commonsubsequence from the beginning of a separate line. <br>
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
算法分析:
最长公共子序列 典型算法 详细解释【点这里】
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define MAX 5005
int f[MAX][MAX];//必须放在外面
int main()
{
int i,j;
string x,y;
while(cin>>x>>y)
{
int lx=x.length();//x序列长度
int ly=y.length();//y序列长度
for(i=1;i<=lx;i++)
for(j=1;j<=ly;j++)
{
f[i][j]=max(f[i-1][j],f[i][j-1]);
if(x[i-1]==y[j-1])
f[i][j]=max(f[i][j],f[i-1][j-1]+1);
}
printf("%d\n",f[lx][ly]);
}
return 0;
}