Description
The corresponding picture will be as shown below:
Figure 1
If some adjacent boxes are all of the same color, and both the box to its left(if it exists) and its right(if it exists) are of some other color, we call it a ‘box segment’. There are 4 box segments. That is: gold, silver, bronze, gold. There are 1, 4, 3, 1 box(es) in the segments respectively.
Every time, you can click a box, then the whole segment containing that box DISAPPEARS. If that segment is composed of k boxes, you will get k*k points. for example, if you click on a silver box, the silver segment disappears, you got 4*4=16 points.
Now let’s look at the picture below:
Figure 2
The first one is OPTIMAL.
Find the highest score you can get, given an initial state of this game.
Input
Output
Sample Input
2
9
1 2 2 2 2 3 3 3 1
1
1
Sample Output
Case 1: 29
Case 2: 1
分析:
显然,一样颜色的一段区域要一起消,这样贡献才最大
我们可以把一段颜色相同的区域缩成一个点
(后来证明没必要)
我一开始的方程是这样的:
f[i][j] 表示消掉i~j的最大值
如果i和j的颜色一样,那么f[i][j]=f[i+1][j-1]+(len[i]+len[j])^2
否则f[i][j]=max{f[i][k]+f[k+1][j]}
但是可能出现这样的状态:
11221113331
很显然,先消掉2和3,之后一起消掉1才最优
但是要是按照我的转移状态,
只会是消掉22111333之后再消掉最边上的1
所以我们就要改变一下转移的状态:
f[i][j][k] i~j消到只剩下k个,
规定这k个块和i,j的颜色一样
g[i][j] i~j全部消掉的最大值
f[i][j][k]=max{f[i][l][k-1]+g[l+1][j-1]}
表示把l+1~j-1段完全消除,使j与前面颜色相同的k-1个合并,
注意枚举的l必须与i,j颜色相同
g[i][j]=max(g[i][l]+g[l+1][j],f[i][j][k]+k^2)
可以将i~j从中间断开分别消除,也可以将i~j剩下的k个一次消除
tip
g[i][j]=g[i][l]+g[l+1][j]
不牵扯到k,所以可以单独拿出来转移
重申原则
一定要从稳定状态转移
我写出来之后发现跑出来的答案比标准答案大
这时候我发现题解上有一句话
memset(f,128,sizeof(f)); //初始值为-INF
我一开始是把所有f都附成了0
改过来之后就好了
这里写代码片
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int n;
int a[202],tot;
int f[202][202][202],g[202][202];
int doit()
{
int i,j,k,l;
memset(f,128,sizeof(f));
memset(g,0,sizeof(g));
for (i=1;i<=n;i++) g[i][i]=1,f[i][i][0]=0,f[i][i][1]=0;
for (i=n-1;i>=1;i--)
for (j=i+1;j<=n;j++)
{
if (a[i]==a[j]) //col must be same
for (k=1;k<=j-i+1;k++)
{
for (l=i;l<j;l++)
if (a[i]==a[l]) //col must be same
f[i][j][k]=max(f[i][j][k],f[i][l][k-1]+g[l+1][j-1]);
//f[i][j][k]已经固定下来了,才能进行个g[i][j]的转移
g[i][j]=max(g[i][j],f[i][j][k]+k*k);
}
for (k=i;k<j;k++) g[i][j]=max(g[i][j],g[i][k]+g[k+1][j]);
}
return g[1][n];
}
int main()
{
int T;
scanf("%d",&T);
int TT=0;
while (++TT<=T)
{
int x;
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
printf("Case %d: %d
",TT,doit());
}
return 0;
}