链接:戳这里
D. Zuma
time limit per test2 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard 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
3
1 2 1
output
1
input
3
1 2 3
output
3
input
7
1 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个宝石的颜色ci,现在有一个操作,就是子串的颜色是回文串的区间可以通过一次操作消去
问最少需要多少次操作可以消除所有的宝石
思路:
很明显是要dp,而且n=500
那么设置状态的时候dp[i][j] 表示区间[i,j]的最优值
那么怎么转移呢?直接看代码吧!
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
int dp[550][550]; /// 区间[i,j]的最小值
int a[550],n;
int main(){
mst(dp,127);
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
for(int i=0;i<n;i++) dp[i][i]=1; /// 初始化 本身到本身为1
for(int i=1;i<n;i++){ /// 枚举当前区间的长度
for(int j=0;j+i<n;j++){ /// 当前区间[j,j+i]的最小值
if(i==1){ /// 当前长度为1的时候直接判断 后面的区间里面至少长度>2
if(a[j]==a[j+i]) dp[j][j+i]=1;
else dp[j][j+i]=2;
} else {
if(a[j]==a[j+i]) dp[j][j+i]=dp[j+1][j+i-1]; ///首尾相等的话转移到[j+1,j+i-1]区间上去取最优值
for(int k=j;k<j+i;k++){
dp[j][j+i]=min(dp[j][j+i],dp[j][k]+dp[k+1][i+j]);
/// 枚举这个k,有最优的值就更新区间最优值
}
}
}
}
printf("%d\n",dp[0][n-1]);
return 0;
}