CodeForces-607B:Zuma (基础区间DP)

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.

Example

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

题意:给定一排数字串,每次操作可以删去其中一段回文串,问至少需要多少次操作。

思路:区间DP,对长度为1和2的特殊处理:

           如果为1,那么dp[i][i]=1;如果为2。

           如果为2,那么dp[i][j]取决于a[i]和a[j]是否相同。

           否则,先根据边界是否相同初始化,然后区间DP。

当然,也可以用普通DP实现,dp[i]=max(dpx),可以用hash验证后面是否是回文串。(感觉没问题吧。)

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=510;
const int inf=1000000;
int dp[maxn][maxn],a[maxn];
int main()
{
    int N,i,j,k;
    scanf("%d",&N);
    for(i=1;i<=N;i++) scanf("%d",&a[i]);
    for(i=N;i>=1;i--){
        for(j=i;j<=N;j++){
            if(j-i==0) dp[i][j]=1;
            else if(j-i==1) dp[i][j]=(a[i]==a[j])?1:2;
            else {
                if(a[i]==a[j]) dp[i][j]=dp[i+1][j-1];
                else dp[i][j]=dp[i+1][j-1]+2;
                for(k=i;k<j;k++) dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
            }    
        }
    }
    printf("%d
",dp[1][N]);
    return 0;
}
原文地址:https://www.cnblogs.com/hua-dong/p/8568516.html