hdu 1159 Common Subsequence
Problem Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X =
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
题目大意:
求两个字符串的最长公共子序列
题目解析:
当看到这个题目的时候首先想到的就是最长公共子序列,dp[i][j]表示第一个字符串的前i个字符与第二个字符串的前j个字符的最大公共子序列的长度,可以推导出状态转移方程(简单的模板题)
dp[i+1][j+1] = s1[i]==s2[j] ? dp[i][j]+1:max(dp[i][j+1] , dp[i+1][j]);
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 100;
char s1[maxn], s2[maxn];
int len1,len2;
int dp[maxn][maxn];
void solve()
{
for(int i = 0; i < len1; i++)
{
for(int j = 0; j < len2; j++)
{
if(s1[i] == s2[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]);
}
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(cin >> s1 >> s2)
{
memset(dp,0,sizeof(dp));
len1 = strlen(s1);
len2 = strlen(s2);
solve();
cout<<dp[len1][len2]<<endl;
}
return 0;
}
还没有评论,来说两句吧...