hdu 6212 区间dp
题意:祖玛游戏,最少的弹药消除所有珠子
思路:区间dp,注意枚举中间空一个珠子的情况,这里要注意的是中间不能有两个,并且两边的加中间枚举的也不能是三个(因为这样不管先取左右都会直接被消除掉)
代码:
#include<bits/stdc++.h>
using namespace std;
struct node {
int num, color;
}ball[515];
int f[515][515];
int a[515], m, n;
char input[500];
int main(){
int t;
scanf("%d", &t);
int caset = 0;
while (t--){
scanf("%s", input);
n = strlen(input);
for (int i = 1; i <= n; i++)a[i] = input[i - 1] - '0';
int bal = a[1], num = 0;
m = 0;
for (int i = 1; i <= n; i++){
if (a[i] != bal) {
ball[++m].num = num;
ball[m].color = bal;
num = 1;
bal = a[i];
}
else num++;
}
ball[++m].num = num;
ball[m].color = bal;
for (int i = 1; i <= m; i++)
if (ball[i].num > 1)f[i][i] = 1;
else f[i][i] = 2;
for (int p = 2; p <= m; p++){
for (int i = 1; i + p - 1 <= m; i++){
int j = i + p - 1;
f[i][j]=1e9;
if (ball[i].color == ball[j].color){
if (ball[i].num + ball[j].num == 2) f[i][j] = f[i + 1][j - 1] + 1;
else f[i][j] = f[i + 1][j - 1];
for (int k = i + 2; k<j - 1; k++)
if (ball[k].color == ball[i].color&&ball[k].num==1&&(ball[i].num==1||ball[j].num==1))
f[i][j] = min(f[i][j], f[i+1][k-1]+f[k+1][j-1]);
}
for (int k = i; k<j; k++)
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
printf("Case #%d: %d\n", ++caset, f[1][m]);
}
return 0;
}