P1435 [IOI2000] 回文字串

题目:
链接: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;
}

posted on 2024-04-05 21:10  WHUStar  阅读(29)  评论(0编辑  收藏  举报