https://vjudge.net/contest/221629#problem/A
题目意思:
输入几个字符串,判断每个字符串最少切割成几串可以使得每一串都是 回文
Sample Input
3
racecar
fastcar
aaadbccb
Sample Output
1
7
3
使用DP来解决比较好。
用数组dp[i]来保存 从1到 i 个字符,至少需要切割成几个串,使得他们都是回文
这样转移方程就有了:
dp[i]=min(dp[i-1]+1,dp[j-1]+1) (j从0到i1-1枚举,取(j~i)是回文的,求最小)
注意:下标!!!提交了好几次都有错,后来发现会访问dp[-1],所以从dp[1]开始记录,dp[0]=0;
#include <iostream>
#include <string.h>
using namespace std;
#define MAXN 1005
string s;
bool check(int i,int j){
while(i<=j){
if(s[i]!=s[j]) return false;
i++; j--;
}
return true;
}
int main(){
int n;
int dp[MAXN];
cin>>n;
while(n--){
cin>>s;
dp[0]=0;
dp[1]=1;//第一个字符,分为1串
for(int i=1;i<s.length();i++){
dp[i+1]=dp[i]+1;
for(int j=i-1;j>=0;j--){
if(check(j,i)) dp[i+1]=min(dp[i+1],dp[j]+1);
// cout<<dp[i+1]<<" ";
}
}
cout<<dp[s.length()]<<endl;
}
return 0;
}