题目:
链接:https://www.luogu.com.cn/problem/P1435
观察到:在里面插入字符不会影响外面的配对
所以以dp[i][j]记录字符串s下标从i到j变化到回文串步数,那么递推公式:
if(s[i] == s[j])dp[i][j] = dp[i+1][j-1];
else dp[i][j] = min(dp[i+1][j],dp[i][j-1]) + 1;
就是说如果最外面能配对,那么步数就是里面字串的步数
如果不能配对,那么步数就是去掉左/右的步数min + 1
同时设置退出条件即可
代码
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
typedef unsigned long long ll;
using namespace std;
const int N = 1e3 + 2;
string s;
int dp[N][N];
int dfs(int i, int j)
{
if (dp[i][j] != 0)return dp[i][j];//记忆化
if (i >= j)return 0;//退出条件
int res;
if (s[i] == s[j])res = dfs(i + 1, j - 1);
else res = min(dfs(i + 1, j), dfs(i, j - 1)) + 1;
return dp[i][j] = res;
}
int main()
{
getline(cin, s);
int ans = INT_MAX;
cout << dfs(0, s.length() - 1);
return 0;
}
标签:IOI2000,res,dfs,int,P1435,文字串,include,步数,dp
From: https://www.cnblogs.com/zzzsacmblog/p/18116209