codeforces 607B. Zuma

Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.

In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?

Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

Input

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones.

The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.

Output

Print a single integer — the minimum number of seconds needed to destroy the entire line.

Sample test(s)
input
3
1 2 1
output
1
input
3
1 2 3
output
3
input
7
1 4 4 2 3 2 1
output

2


题意:给你一个长度为n的字符串,每次你可以消去一段连续的回文子串,剩下的两端重新拼接成一个新的串,问最少需要消去多少次。

思路:这题一开始想不出,不好dp,一个明显的思路是用dp[i][j]表示消去i到j段最少要的次数,但是不知道每次消去后剩下的串的回文串情况,所以我们要换一个思路。其实题目中的回文串已经提醒我们字符串中的每一个字符都要和别的字符匹配后才能消除,那么对于dp[i][j],我们考虑左端点,它被消去只有两种情况,一种是单独消去,另一种是和别的字符匹配消去,第一种情况比较简单,那么对于第二种情况,我们可以枚举[i,j]区间内每一个和它相同的点k,然后先消去区间[i+1,k-1],最后再消去i和k,其实[i+1,k-1]中最后消去的肯定是回文串,一个回文串两端加两个相同的点也是回文串,可以一次消去,所以这里dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k+1][j]);注意还要特判k=i+1的情况。


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
#define inf 99999999
#define pi acos(-1.0)
int dp[600][600],a[600];
int main()
{
    int n,m,i,j,len,k;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=1;i<=n;i++){
            scanf("%d",&a[i]);
            dp[i][i]=1;
        }
        for(i=1;i<=n-1;i++){
            if(a[i]==a[i+1])dp[i][i+1]=1;
            else dp[i][i+1]=2;
        }
        for(len=3;len<=n;len++){
            for(i=1;i+len-1<=n;i++){
                j=i+len-1;
                dp[i][j]=inf;
                dp[i][j]=min(dp[i][j],dp[i+1][j]+1);
                if(a[i]==a[i+1]){
                    dp[i][j]=min(dp[i][j],dp[i+2][j]+1);
                }
                if(a[i]==a[j]){
                    dp[i][j]=min(dp[i][j],dp[i+1][j-1]);
                }
                for(k=i+2;k


转载于:https://www.cnblogs.com/herumw/p/9464572.html

你可能感兴趣的:(codeforces 607B. Zuma)