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.ios

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?ui

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.this

Inputspa

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

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.orm

Outputblog

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

Examplerem

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

題意:給定一排數字串,每次操做能夠刪去其中一段迴文串,問至少須要多少次操做。input

思路:區間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\n",dp[1][N]); return 0; }
相關文章
相關標籤/搜索