动态规划——最长公共子序列问题

56 阅读1分钟
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    string a, b;
    int i, j, len_a, len_b;
    int temp[499][499];

    while (cin >> a >> b)
    {
        len_a = a.length();
        len_b = b.length();
        memset(temp, 0, sizeof(temp));
        for (i = 1; i <= len_a; i++)
        {
            for (j = 1; j <= len_b; j++)
            {
                if (a[i - 1] == b[j - 1])
                    temp[i][j] = temp[i - 1][j - 1] + 1;
                else
                    temp[i][j] = temp[i - 1][j] > temp[i][j - 1] ? temp[i - 1][j] : temp[i][j - 1];
            }
        }
        cout << temp[len_a][len_b] << endl;
    }
}