Codeforces Round #336 (Div. 2)-D Zuma(区间DP)

来源:互联网 发布:安卓好用的拼长图软件 编辑:程序博客网 时间:2024/06/06 00:31
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

题意:给你n个数,每次可以选择一个回文子串消除,然后剩下的序列自动按顺序组成串,重复操作,问你最少删多少次可以消完。

题解:裸的区间DP。。

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int a[505],dp[505][505];int main(void){int n,i,j,k,len;scanf("%d",&n);for(i=1;i<=n;i++)scanf("%d",&a[i]);memset(dp,127,sizeof(dp));for(i=1;i<=n;i++)dp[i][i]=1;for(len=2;len<=n;len++)for(i=1;i+len-1<=n;i++){j=i+len-1;for(k=i;k<j;k++)dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);if(a[i]==a[j]){if(i+1==j)dp[i][j]=1;dp[i][j]=min(dp[i+1][j-1],dp[i][j]);  }}printf("%d\n",dp[1][n]);return 0;}