## Sunday, December 27, 2015

### Codeforces 607B Zuma (区间DP)

http://codeforces.com/problemset/problem/607/B
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has colorci. 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.
Sample test(s)
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.

http://winterfell30.com/2015/12/24/cf607B/

1.l == r, 那他本身是一个回文串，返回1即可。
2.l > r,不是一个串，返回0。
3.没有什么特征的，dp[l][r] = dp[l+1][r] + 1。
4.在l+2到r中枚举和a[l]相等的a[k]，分成l到k和k+1到r的串dp[l][r] = dp[l][k-1] + dp[k+1][r]。
5.这里有个特殊情况就是当存在两个相邻的相同数字时，这时候他是一个回文串，但是上面转移都无法正确处理，所以当dp[l] == dp[l+1]时，dp[l][r] = dp[l+2][r] + 1。
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
int f[510][510];
int a[510];
int dp(int l, int r)
{
if (l == r) return 1;
if (l > r) return 0;
if (f[l][r] != INF) return f[l][r];
f[l][r] = min(f[l][r], dp(l + 1, r) + 1);
for (int i = l + 2; i <= r; i++) if (a[l] == a[i])
{
f[l][r] = min(f[l][r], dp(l + 1, i - 1) + dp(i + 1, r));
}
if (a[l] == a[l+1]) f[l][r] = min(f[l][r], dp(l + 2, r) + 1);
return f[l][r];
}
int main()
{
//freopen("H:\\in.txt","r",stdin);
//freopen("H:\\out.txt","w",stdout);
int n;
scanf("%d", &n);
memset(f, INF, sizeof(f));
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
printf("%d\n", dp(1, n));
return 0;
}