题目传送门poj1390 题 目 传 送 门 p o j 1390
题目
Blocks B l o c k s
TimeLimit:5000MS
T
i
m
e
L
i
m
i
t
:
5000
M
S
MemoryLimit:65536K
M
e
m
o
r
y
L
i
m
i
t
:
65536
K
TotalSubmissions:6118
T
o
t
a
l
S
u
b
m
i
s
s
i
o
n
s
:
6118
Accepted:2523
A
c
c
e
p
t
e
d
:
2523
Description D e s c r i p t i o n
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:
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:
The first one is OPTIMAL.
Find the highest score you can get, given an initial state of this game.
Input I n p u t
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 O u t p u t
For each test case, print the case number and the highest possible score.
SampleInput S a m p l e I n p u t
2
9
1 2 2 2 2 3 3 3 1
1
1
SampleOutput S a m p l e O u t p u t
Case 1: 29
Case 2: 1
题解
这道题是一道看起来很简单的难题。
由于贪心,我们可以发现:颜色一样位置相邻的块可以直接合并,预处理掉即可。
然后我们设计状态:
f[i][j]
f
[
i
]
[
j
]
表示
i
i
到合并后的最大分数,但是我们发现无法转移,因为存在多段颜色都一样位置不相邻的块合并的情况。
所以我们需要重新设计状态:
f[i][j][k]
f
[
i
]
[
j
]
[
k
]
表示
i
i
到,并且在
j
j
位置中加长颜色相同的块,合并后的最大分数。
这样就容易转移了:
1.
1.
如果
j
j
自己合并,那么。
2.
2.
如果
j
j
与别人合并,那么枚举与一起合并的别人
p
p
,,
i≤p<j
i
≤
p
<
j
且
col[p]=col[j]
c
o
l
[
p
]
=
c
o
l
[
j
]
。
这样就完美解决了。
标程
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 250;
int main() {
int t; cin >> t;
static int f[N][N][N];
static int n, m, c[N], d[N], e[N];
for (int tt = 1; tt <= t; tt++) {
cin >> n; m = 0; e[0] = n;
memset(d, 0, sizeof d);
for (int x, i = 1; i <= n; i++) {
cin >> x;
if (x != c[m]) {
c[++m] = x;
e[m] = e[m - 1];
}
d[m]++; e[m]--;
}
for (int i = m; i; i--) {
for (int j = i; j <= m; j++) {
for (int k = 0; k <= e[j]; k++) {
f[i][j][k] = f[i][j - 1][0] + (d[j] + k) * (d[j] + k);
for (int l = i; l < j; l++) {
if (c[j] != c[l]) continue;
f[i][j][k] = max(f[i][j][k], f[i][l][d[j] + k] + f[l + 1][j - 1][0]);
}
}
}
}
cout << "Case " << tt << ": " << f[1][m][0] << endl;
}
return 0;
}