动态规划练习 11

题目:AGTC (POJ 3356)

链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=3356

#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int matrix[1001][1001];
 
int main(int argc, char **argv)
{
    int m;
    string a, b;
 
    // Got a WA without while loop.
    while (cin >> m >> a >> m >> b)
    {
        for (size_t i = 1; i <= a.size(); ++i)
        {
            matrix[i][0] = i;
        }
 
        for (size_t j = 1; j <= b.size(); ++j)
        {
            matrix[0][j] = j;
        }
 
        for (size_t i = 1; i <= a.size(); ++i)
        {
            for (size_t j = 1; j <= b.size(); ++j)
            {
                if (a[i - 1] != b[j - 1])
                {
                    int dist = min(matrix[i - 1][j], matrix[i][j - 1]);
                    matrix[i][j] = min(dist, matrix[i - 1][j - 1]) + 1;
                }
                else
                {
                    int dist = min(matrix[i - 1][j], matrix[i][j - 1]) + 1;
                    matrix[i][j] = min(dist, matrix[i - 1][j - 1]);
                }
            }
        }
 
        cout << matrix[a.size()][b.size()] << endl;
    }
 
    return 0;
}

你可能感兴趣的:(动态规划)