题意:
给定一个字符串,求能分成最小几个回文串
分析:简单dp dp[i]前i个字符能分成的最小数量 dp[i]=min(dp[i],dp[j-1]+1) (j-i 是回文串)
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <string> #include <cctype> #include <complex> #include <cassert> #include <utility> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; typedef pair<int,int> PII; typedef long long ll; #define lson l,m,rt<<1 #define pi acos(-1.0) #define rson m+1,r,rt<<11 #define All 1,N,1 #define read freopen("in.txt", "r", stdin) const ll INFll = 0x3f3f3f3f3f3f3f3fLL; const int INF= 0x7ffffff; const int mod = 1000000007; int dp[1010]; char s[1010]; int judge(int x,int y){ while(x<y){ if(s[x]!=s[y])return 0; x++;y--; } return 1; } int main() { int t; scanf("%d",&t); while(t--){ scanf("%s",(s+1)); int len=strlen(s+1); for(int i=1;i<=len;++i) dp[i]=INF; dp[0]=0; for(int i=1;i<=len;++i) for(int j=1;j<=i;++j) if(judge(j,i)){ dp[i]=min(dp[i],dp[j-1]+1); } printf("%d\n",dp[len]); } return 0; }
时间: 2024-10-18 02:09:43