最长公共子序列问题

来源:互联网 发布:公务员面试报网络班 编辑:程序博客网 时间:2024/06/07 07:35

Problem Description
给定两个序列X=
Input
输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。
Output
每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。
Example Input
ABCBDAB
BDCABA
Example Output
4

#include <iostream>  #include<algorithm>#include<cstring>#include<string>using namespace std;int dp[550][550];//放在main函数外面,否则会溢出int main() {    string x, y;    while (cin >> x >> y) {        memset(dp, 0, sizeof(dp));        int len1 = x.size();        int len2 = y.size();        for (int i = 1; i <= len1; i++)            for (int j = 1; j <= len2; j++) {                if (x[i - 1] == y[j - 1])                    dp[i][j] = dp[i - 1][j - 1] + 1;                else                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);            }        cout << dp[len1][len2] << endl;    }    return 0;}
原创粉丝点击