CF607B

Zuma

题面翻译

题目描述

Genos最近在他的手机上下载了祖玛游戏。在祖玛游戏里,存在n个一行的宝石,第i个宝石的颜色是Ci 。这个游戏的目标是尽快的消灭一行中所有的宝石。 在一秒钟,Genos能很快的挑选出这些有颜色的宝石中的一个回文的,连续的子串,并将这个子串移除。每当一个子串被删除后,剩余的宝石将连接在一起,形成一个新的行列。你的任务是:求出把整个宝石串都移除的最短时间。 让我们给你一个提示:如果一个串正着读或倒着读都一样,那么这个串(或子串)叫回文串。在我们这道题中,“回文”指这个宝石串中的第一个珠子的颜色等于最后一个珠子的颜色,第二个珠子的颜色等于倒数第二个珠子的颜色,等等。
输入输出格式
输入格式:

第一行包含一个整数n(1<=n<=500) ——宝石串的长度。 第二行包含n个被空格分开的整数,第i(1<=i<=n) 个表示这行中第i个珠子的颜色。
输出格式:

输出一个整数,把这行珠子移除的最短时间。 (样例略)
说明:

在第一个例子中,Genos可以在一秒钟就把这行珠子全部移走。 在第二个例子中,Genos一次只能移走一个珠子,所以移走三个珠子花费他三秒。 在第三个例子中,为了达到2秒的最快时间,先移除回文串4 4,再移除回文串1 2 3 2 1。

输入格式

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 $ c_{i} $ ( $ 1<=c_{i}<=n $ ) — the color of the $ i $ -th gemstone in a line.

输出格式

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

样例 #1

样例输入 #1

3
1 2 1

样例输出 #1

1

样例 #2

样例输入 #2

3
1 2 3

样例输出 #2

3

样例 #3

样例输入 #3

7
1 4 4 2 3 2 1

样例输出 #3

2

提示

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.

啊我真的服了区间DP了
这题回文的处理属实离谱
if(a[l]==a[r])f[l][r]=f[l+1][r-1]

因为l+1~r-1最后一次消除的肯定是一个回文串 那么加上a[l] a[r]也是一个回文串 所以可以一并消掉!!!

然后按照区间DP套路即可
点击查看代码
#include<bits/stdc++.h>
using namespace std;
int n,a[505],f[505][505];
int main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	memset(f,0x3f,sizeof(f));
	for(int i=1;i<=n;i++)f[i][i]=1,f[i][i+1]=1+(a[i]!=a[i+1]);
	for(int l=3;l<=n;l++)
		for(int i=1;i+l-1<=n;i++)
		{
			int j=i+l-1;
			if(a[i]==a[j])f[i][j]=f[i+1][j-1];
			for(int k=i;k<j;k++)
				f[i][j]=min(f[i][j],f[i][k]+f[k+1][j]);
		}
	cout<<f[1][n]<<"\n";
	return 0;
}
posted @ 2023-01-17 22:48  PKU_IMCOMING  阅读(5)  评论(0)    收藏  举报