LightOJ 1044 - Palindrome Partitioning【dp】

題目鏈接:http://www.lightoj.com/volume_showproblem.php?problem=1044

題意:給你一個字符串,問最少分爲幾個迴文串?

思路:dp[i]表示從開頭到位置 i 的最優解,若[j,i]是迴文串,則dp[i] = min(dp[i],dp[j-1] +1)

代碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <string>

using namespace std;

char s[1010];
int dp[1010];

bool is_ok(char a[], int L, int R)
{
    while (L <= R)
    {
        if (a[L] != a[R])
        {
            return false;
        }
        L++;
        R--;
    }

    return true;
}

int main()
{
    int T;
    scanf("%d", &T);
    for (int t = 1;t <= T;t++)
    {
        memset(dp, 0, sizeof(dp));

        scanf("%s", s + 1);
        int len = strlen(s+1);

        for (int i = 1;i <= len;i++)
        {
            dp[i] = 1010;
            for (int j = 1;j <= i;j++)
            {
                if (is_ok(s, j, i))
                {
                    if (j == 1)
                        dp[i] = 1;
                    else
                        dp[i] = min(dp[i], dp[j - 1] + 1);
                }
            }
        }

        printf("Case %d: %d\n", t, dp[len]);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章