题意:输入一个由小写字母组成的字符串,你的任务是把它划分成尽量少的回文串,字符串长度不超过1000。
分析:
1、dp[i]为字符0~i划分成的最小回文串的个数。
2、dp[j] = Min(dp[j], dp[i - 1] + 1),若i~j是回文串,则更新dp[j]。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) const double eps = 1e-8; inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const int MAXN = 1000 + 10; const int MAXT = 10000 + 10; using namespace std; char s[MAXN]; int dp[MAXN]; bool judge(int l, int r){ int len = r - l + 1; for(int i = 0; i < len / 2; ++i) if(s[l + i] != s[r - i]) return false; return true; } int main(){ int T; scanf("%d", &T); while(T--){ memset(dp, INT_INF, sizeof dp); scanf("%s", s + 1); int len = strlen(s + 1); dp[0] = 0; for(int i = 1; i <= len; ++i){ for(int j = i; j <= len; ++j){ if(judge(i, j)){ dp[j] = Min(dp[j], dp[i - 1] + 1); } } } printf("%d\n", dp[len]); } return 0; }