Codeforces Round #336 (Div. 2)D. Zuma【区间dp】

来源:互联网 发布:java log4j tcp 编辑:程序博客网 时间:2024/05/19 18:42

D. Zuma
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

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.

Examples
input
31 2 1
output
1
input
31 2 3
output
3
input
71 4 4 2 3 2 1
output
2
Note

In the first sample, Genos can destroy the entire line in one second.

In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.

In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

题意:给出一个序列每次可以从中删除一个回文序列删除一个回文序列后剩下的序列重现组成一个序列问最少需要的删除次数

解题思路:区间dp

/* ***********************************************Author       : rycCreated Time : 2016-08-21 SundayFile Name    : E:\acm\codeforces\336D.cppLanguage     : c++Copyright 2016 ryc All Rights Reserved************************************************ */#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>#include<cmath>#include<queue>#include<list>#include<vector>#include<stack>using namespace std;typedef long long LL;typedef pair<int,int>pii;const int maxn=510;int num[maxn];int dp[maxn][maxn];int main(){    int n;cin>>n;    memset(dp,0x3f,sizeof(dp));    for(int i=1;i<=n;++i){        scanf("%d",&num[i]);dp[i][i]=1;    }    for(int len=2;len<=n;++len){//枚举区间长度        for(int l=1;l<=n-len+1;++l){//枚举区间左端点            int r=l+len-1;            for(int k=l;k<r;++k){                dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r]);            }            if(num[l]==num[r]){                if(l+1==r){dp[l][r]=1;}                dp[l][r]=min(dp[l][r],dp[l+1][r-1]);            }        }    }    printf("%d\n",dp[1][n]);    return 0;}


0 0