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
3
1 2 1
1
3
1 2 3
3
7
1 4 4 2 3 2 1
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; }