其他分享
首页 > 其他分享> > 密码脱落 (区间DP)

密码脱落 (区间DP)

作者:互联网

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1005;
char str[N];
int dp[N][N];

int main()
{
    memset(dp, 0x3f, sizeof dp);
    cin >> str + 1;
    int n = strlen(str + 1);
    for(int i = 1; i <= n; i++) dp[i][i] = 0;
    for(int len = 2; len <= n; len ++)
    {
        for(int l = n - len + 1; l >= 1 ; l--)
        {
            int r = l + len - 1;
            if(str[l] == str[r])
            {
                if(l + 1 <= r - 1) dp[l][r] = dp[l+1][r-1];
                else dp[l][r] = 0;
            }
            else dp[l][r] = min(dp[l+1][r] + 1, dp[l][r-1] + 1);
//            cout << "l = " << l << " r = "  << r << " val= " << dp[l][r] << endl;
        }
    }
    cout << dp[1][n];
    return 0;
}

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1005;
char str[N];
int dp[N][N];
int dfs(int l , int r)
{
    if(l >= r) return dp[l][r] = 0;
    if(dp[l][r] != 0x3f3f3f3f) return dp[l][r];
    if(str[l] == str[r]) dp[l][r] = dfs(l + 1, r - 1);
    else dp[l][r] = min(dfs(l, r - 1) + 1, dfs(l + 1, r) + 1);
    return dp[l][r];
}
int main()
{
    memset(dp, 0x3f, sizeof dp);
    cin >> str + 1;
    int n = strlen(str + 1);
    int res = dfs(1, n);
    cout << res;
    return 0;
}

标签:return,int,脱落,dfs,密码,DP,str,include,dp
来源: https://www.cnblogs.com/K2MnO4/p/14850857.html