Some of you may have played a game called ‘Blocks’. There are n blocks in a row, each box has a color. Here is an example: Gold, Silver, Silver, Silver, Silver, Bronze, Bronze, Bronze, Gold.
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.
The first line contains the number of tests t(1<=t<=15). Each case contains two lines. The first line contains an integer n(1<=n<=200), the number of boxes. The second line contains n integers, representing the colors of each box. The integers are in the range 1~n.
For each test case, print the case number and the highest possible score.
2
9
1 2 2 2 2 3 3 3 1
1
1
Case 1: 29
Case 2: 1
给定n个不同颜色的盒子,连续的相同颜色的k个盒子可以拿走,权值为k*k,求把所有盒子拿完的最大权值。
合并初始相邻相同的块,得到颜色数组c和对应的长度len.
例如 1 1 1 1 1 3 2 2 1 1 1 可记为 color[1]=1 ; len[1]=5 ; color[2]=3 ; len[2]=1 ; color[3]=2 ; len[3]=2 ; color[4]=1 ; len[4]=3 ;
d[i][j][k] 表示i~j区间,与后面k个相同颜色块一起消除得分的最大值(当然k个块的颜色必须与j相同),写代码的时候,k段和 j 那段不必挨在一起,因为你本来就假设他们之间的那段被消掉了,
状态转移方程两种:
1.单独消除, dp[i][j][k]=dp[i][j−1][0]+(len[j]+k)2 ;
2.和区间段 (i,j) 中的某一块进行消除(要颜色一样能消除),假设 i≤p<j 满足条件,则 dp[i][j][k]=dp[i][p][k+len[j]]+dp[p+1][j−1][0] 。
#include
#include
#include
#include
const int size = 200+10;
int len[size],f[size][size][size],n;
int color[size],flag;
int T,ans,tmp;
inline int dp(int x,int y,int k) {
if(f[x][y][k]) return f[x][y][k];
if(x==y) return (len[x]+k)*(len[x]+k);
f[x][y][k]=dp(x,y-1,0)+(len[y]+k)*(len[y]+k);
for(int i=x;iif(color[y]==color[i])
f[x][y][k]=std::max(f[x][y][k],dp(x,i,len[y]+k)+dp(i+1,y-1,0));
}
return f[x][y][k];
}
int main() {
scanf("%d",&T);
for(int t=1;t<=T;t++) {
scanf("%d",&n);flag=0;
memset(len,0,sizeof len);
memset(color,0,sizeof color);
for(int i=0;iscanf("%d",&tmp);
if(color[flag]==tmp) len[flag]++;
else { flag++;len[flag]++;color[flag]=tmp; }
}
memset(f,0,sizeof f);
ans=dp(1,flag,0);
printf("Case %d: ",t);printf("%d\n",ans);
}
return 0;
}