Partitioning by Palindromes UVA - 11584
题意:
将一个串划分为最少的回文串。
思路:
- dp【i】第i个位置的最小划分。
- 转移方程dp【i】=min(dp【j-1】+1, s [ j − > i ] s[j->i] s[j−>i]是回文串)。
- 对于上面的判断回文,可以打表预处理。
AC
#include <iostream>
#include <bits/stdc++.h>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
#define rep(i,y,x) for(int i=(y); i>=(x); i--)
#define mst(x,a) memset(x,a,sizeof(x))
#define pb push_back
#define sz(a) (int)a.size()
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int,int>pa;
typedef pair<ll,ll>pai;
const int maxn = 1100;
int hui[maxn][maxn], dp[maxn];
char s[maxn];
int main()
{
// ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int tt; scanf("%d", &tt);
while(tt--){
scanf("%s", s+1);
int n = strlen(s+1);
For(i,1,n)For(j,1,n)hui[i][j]=0,dp[i]=i;
For(i,1,n){
int p, q;
q = p = i;
while( p>=1 && q<=n && s[p]==s[q])hui[p][q] = 1,p--, q++;
p = i; q = i+1;
while( p>=1 && q<=n && s[p]==s[q])hui[p][q] = 1,p--, q++;
}
For(i,1,n)For(j,1,i)if(hui[j][i])dp[i] = min(dp[i], dp[j-1] + 1);
printf("%d\n", dp[n]);
}
return 0;
}