您的位置:首页 > 其它

UVA11584 划分成回文串

2016-02-03 18:35 393 查看
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105116#problem/B

紫书275

题意:输入一个字符,最少能划分几个回文串

分析:预处理一下,判断i,j是否为回文串;动态分析求解,dp[i] = dp[i - 1] + 1,假设i单独成为一个回文串,然后在往前找,如果j到i是回文,dp[i] = min(dp[i], dp[j - 1] + 1)

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX = 1000 + 10;
const int INF = 0x3f3f3f3f;
char s[MAX];
int dp[MAX],len,is_h[MAX][MAX];
void judge_huiwen()
{
int x,y;
memset(is_h, 0, sizeof(is_h));
for(int i = 1; i <= len; i++)
{
x = i - 1;
y = i + 1;
while(x > 0 && y <= len && s[x] == s[y])
{
is_h[x][y] = 1;
x--;
y++;
}
x = i;
y = i + 1;
while(x > 0 && y <= len && s[x] == s[y])
{
is_h[x][y] = 1;
x--;
y++;
}
}
}
int main()
{
int test;
scanf("%d", &test);
while(test--)
{
scanf("%s", s + 1);
len = strlen(s + 1);
memset(dp,0,sizeof(dp));
dp[1] = 1;
judge_huiwen();
for(int i = 2; i <= len; i++)
{
dp[i] = dp[i - 1] + 1;
for(int j = i - 1; j > 0; j--)
{
if(is_h[j][i])
{
dp[i] = min(dp[i], dp[j - 1] + 1);
}
}
}
printf("%d\n",dp[len]);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: