当前位置: 代码迷 >> 综合 >> Blocks
  详细解决方案

Blocks

热度:90   发布时间:2023-11-22 14:03:03.0

题目链接
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 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.

Input
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.

Output
For each test case, print the case number and the highest possible score.
Sample Input

2
9
1 2 2 2 2 3 3 3 1
1
1

Sample Output

Case 1: 29
Case 2: 1

来自课件

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

AC代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct Box{int color,len;
}box[205];
int t,n,x,y,idx,dp[205][205][205];
int click_box(int i,int j,int len){if(dp[i][j][len])return dp[i][j][len];if(i == j)return dp[i][j][len] = (box[j].len + len) * (box[j].len + len);dp[i][j][len] = click_box(i,j - 1,0) + (box[j].len + len)*(box[j].len + len);//点击最后一个盒子for(int k = i;k <= j - 1;k++)if(box[k].color == box[j].color)//为什么不是box[k] + len ? box[j].len + len是k右边的大块进行合并的长度,k合不合并分两种,取最优dp[i][j][len]=max(dp[i][j][len],click_box(i,k,box[j].len+len)+click_box(k+1,j-1,0));return dp[i][j][len];
}
int main(){scanf("%d",&t);for(int i = 1;i <= t;i++){
   //多组输入的时候初始化一定要注意!!!scanf("%d",&n);idx = 0,y = -1;memset(dp,0,sizeof(dp));  //初始化memset(box,0,sizeof(box));//初始化for(int j = 1;j <= n;j++){scanf("%d",&x);if(x != y){idx++;box[idx].len++;box[idx].color = x;y = x;}elsebox[idx].len++;}printf("Case %d: %d\n",i,click_box(1,idx,0));}return 0;
}
  相关解决方案