Poj 1390 Blocks
【关键字】
DP 记忆化搜索
【摘要】
给你一行方块,每个方块都有自己的颜色,连续的同色方块可以消除,得到的分数是个数x^2,求消除所有方块后的得分最大值。
【正文】
1、题目描述
Blocks
Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 1916 Accepted: 734
Description
Some of you may have played a game called'Blocks'. There are n blocks in a row, each box has a color. Here is anexample: Gold, Silver, Silver, Silver, Silver, Bronze, Bronze, Bronze, Gold.
The corresponding picture will be as shownbelow:
Figure 1
If some adjacent boxes are all of the samecolor, 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 thesegments respectively.
Every time, you can click a box, then thewhole segment containing that box DISAPPEARS. If that segment is composed of kboxes, you will get k*k points. for example, if you click on a silver box, thesilver 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, givenan initial state of this game.
Input
The first line contains the number of testst(1<=t<=15). Each case contains two lines. The first line contains aninteger n(1<=n<=200), the number of boxes. The second line contains nintegers, representing the colors of each box. The integers are in the range1~n.
Output
For each test case, print the case numberand the highest possible score.
SampleInput
2
9
1 2 2 2 2 3 3 3 1
1
1
SampleOutput
Case 1: 29
Case 2: 1
Source
Source
lrj黑书
2、算法分析
根据小方块的规则,连在一起的相同颜色的方块可以合并。color[i]表示第i段颜色,len[i]表示第i段的方块的长度。
f[I,j,k]表示把(color[i],len[i]),(color[i+1],len[i+1]),……(color[j-1],len[j-1]),(color[j],color[j]+k)合并的得分。
考虑(color[j],len[j]+k)这段,要么马上消掉,要么和前面若干段一起消掉
1.马上消掉 f[I,j-1,0]+(len[j]+k)^2;
2.若干段,若干段最后面的那一段是p, f[I,p,k+len[j]]+f[p+1,j-1,0];
f[I,j,k]=max{ f[I,j-1,0]+(len[j]+k)^2, f[I,p,k+len[j]]+f[p+1,j-1,0]} (color[p]==color[j])
边界 f[I,i-1,0]=0
3、源码
#include <cstdio>
#include <cstring>
#define MAXN 210
#define INF -1
int color[MAXN],len[MAXN];
int n,num;
int f[MAXN][MAXN][MAXN];
void init()
{
memset(f,-1,sizeof(f));
scanf("%d",&n);
int temp;
scanf("%d",&temp);
color[1]=temp;
len[1]=1;
num=1;
for(int i=2;i<=n;i++)
{
scanf("%d",&temp);
if (temp==color[num])
len[num]++;
else
{
num++;
color[num]=temp;
len[num]=1;
}
}
}
int dpit(int i,int j,int k)
{
if (f[i][j][k]!=-1)
return f[i][j][k];
if (i==j+1) return 0;
int ans=INF;
int temp=dpit(i,j-1,0)+(len[j]+k)*(len[j]+k);
if (temp>ans)
ans=temp;
for(int p=i;p<j;p++)
if (color[p]==color[j])
{
temp=dpit(i,p,len[j]+k)+dpit(p+1,j-1,0);
if (temp>ans)
ans=temp;
}
f[i][j][k]=ans;
return ans;
}
int main()
{
int t;
scanf("%d",&t);
for (int i=1;i<=t;i++)
{
init();
int ans=dpit(1,num,0);
printf("Case %d: %d\n",i,ans);
}
return 0;
}