LightOJ - 1044 Palindrome Partitioning(DP)

来源:互联网 发布:php mvc框架 编辑:程序博客网 时间:2024/05/18 03:58

题目大意:给你一个字符串,要求你对字符串进行划分,使得划分出来的子串都是回文串,且子串数量达到最小

解题思路:用dp[i]表示前i个字符划分成回文串,需要划分成多少个部分
接着枚举j,如果[i,j]回文,那么dp[i] = min(dp[i], dp[j - 1] + 1)

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int INF = 0x3f3f3f3f;const int N = 1010;char str[N];int dp[N];int cas = 1;bool judge(int i, int j) {    while (i <= j) {        if (str[i] != str[j]) return false;        i++; j--;    }    return true;}void solve() {    scanf("%s", str);    int len = strlen(str);    for (int i = 0; i < len; i++) {        dp[i] = INF;        for (int j = 0; j <= i; j++) {            if (judge(j, i)) {                if (j == 0) dp[i] = 1;                else dp[i] = min(dp[i], dp[j - 1] + 1);            }        }    }    printf("Case %d: %d\n", cas++, dp[len - 1]);}int main() {    int test;    scanf("%d", &test);    while (test--) solve();    return 0;}
0 0
原创粉丝点击