[UVA][dp] 10559 - Blocks
Problem A
Blocks
Input: Standard Input
Output: Standard Output
Time Limit: 10 Seconds
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 Output for Sample Input
2 9 1 2 2 2 2 3 3 3 1 1 1 |
Case 1: 29 Case 2: 1 |
Problemsetter: Rujia Liu, Member of Elite Problemsetters' Panel
Special Thanks: Cailiang Liu & Rongjing Xiang from IOI2003 China National Training Team
題目描述:
一維空間的消去遊戲,每次消去時都會將鄰近相同的消去,並且將剩餘的合併。
消去時獲得的分數為個數的平方。
求最大得分。
題目解法:
// 這題相當地難設計狀態,非常有挑戰性。
1. 先將輸入壓縮成連續的區段個數與顏色 A[], B[] // A : 顏色, B : 個數
2. 考慮最左邊的連續區段要消還是不消,如果不消的話,則將會與另一個串接之後消去。
dp[i][j][k] 表示區段 [i, j] 這時左邊接了 k 個與 A[i] 相同顏色的最大得分。
3. 如果消去最左邊,則得分 = (B[i] + k)^2 + dp[i+1][j][0]
4. 如果不消的話,得分 = max(dfs(i+1, pos-1, 0) + dfs(pos, j, k + B[i]))
則會與 A[pos] == A[i] // 顏色相同的那一串接在一起消去。
#include <stdio.h>
#include <algorithm>
using namespace std;
int A[205], B[205];
int dp[205][205][205]; //[l][r][___{l, r}]
char used[205][205][205] = {}, usedcases = 0;
int dfs(int l, int r, int sl) {
if(l > r) return 0;
if(used[l][r][sl] == usedcases)
return dp[l][r][sl];
int &ret = dp[l][r][sl];
ret = 0;
used[l][r][sl] = usedcases;
ret = dfs(l+1, r, 0) + (B[l] + sl)*(B[l] + sl);
for(int i = l+1; i <= r; i++) {
if(A[i] == A[l]) {
ret = max(ret, dfs(l+1, i-1, 0) + dfs(i, r, sl + B[l]));
}
}
return ret;
}
int main() {
int testcase, n, m;
int i, j, k, cases = 0;
scanf("%d", &testcase);
while(testcase--) {
scanf("%d", &n);
for(i = 0; i < n; i++)
scanf("%d", &A[i]);
for(i = 1, B[0] = 1, m = 0; i < n; i++) {
if(A[m] == A[i])
B[m]++;
else {
A[++m] = A[i], B[m] = 1;
}
}
usedcases++;
printf("Case %d: %d\n", ++cases, dfs(0, m, 0));
}
return 0;
}
/*
2
9
1 2 2 2 2 3 3 3 1
1
1
*/