code[vs]3301 Square words

暴力枚举+最长公共子序列

#include <iostream>
#include <cstring>

using namespace std;

int dp[510][510];
int n;

int lcs(char * a, char * b, int lena, int lenb)
{
    memset(dp, 0, sizeof(dp));
    for (int i = 1; i <= lena; i++)
    {
        for (int j = 1; j <= lenb; j++)
        {
            //递推公式
            if (a[i - 1] == b[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[" << lena << "][" << lenb << "]=" << dp[lena][lenb] << endl;
    return (n - 2 * dp[lena][lenb]);
}

int main()
{
    char str[510];

    cin >> n;
    int ans = n;
    cin >> str;
    for (int i = 1; i < n; i++)
    {
        ans = min(ans, lcs(str, str + i, i, n - i));
        //cout << "ans = " << ans << endl;
    }
    cout << ans;
    return 0;
}
posted @ 2015-03-07 20:52  我不吃饼干呀  阅读(161)  评论(0编辑  收藏  举报