hdu6212 区间dp

Zuma

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 367    Accepted Submission(s): 105


Problem Description
Think about the Zuma Game. You have a row of at most  200  black(0) or white(1) balls on the table at the start. Each three consecutive balls never share the same colour. You also have infinite amount of black and white balls in your hand. On each turn, you can choose a ball in your hand and insert it into the row, including the leftmost place and the rightmost place. Then, if there is a group of three of more balls in the same colour touching, remove these balls. Keep doing this until no more balls can be removed.
Find the minimal balls you have to insert to remove all the balls on the table.
 

Input
The first line of input contains an integer  T (1T100)  which is the total number of test cases.
Each test case contains a line with a non-empty string of  0  and  1  describing the row of balls at the start.
 

Output
For each test case, output the case number and the minimal balls required to insert in a line.
 

Sample Input
  
  
4 10101 101001001 1001001001 01001101011001100
 

Sample Output
  
  
Case #1: 4 Case #2: 3 Case #3: 3 Case #4: 2
 

Source
消方块,3个或以上同色可以消除
方法:
1.左右分成两个区间分别消除
2.两端同色,先消除中间,两端合并
3.两端同色并且有一段只有一个方块,在中间找一个同色,两端加中间一起合并(如果两端都是两个不能跟中间合并,因为中间最少有一个,当中间的和两边任意一端合并时都会消除从而无法再与另一端合并了)
#include<bits/stdc++.h>
using namespace std;
const int N =1011;
char ch[N];
int num[N];
int dp[N][N];
int main()
{
    int t;
    scanf("%d",&t);
    for(int cas=1;cas<=t;cas++)
    {
        scanf("%s",ch);
        int n=strlen(ch);
        int l=0;
        num[++l]=1;
        for(int i=1;ch[i]!='\0';i++)
        {
            if(ch[i]!=ch[i-1])num[++l]=0;
            num[l]++;
        }
        for(int i=l;i>=1;i--)
        {
            for(int j=i;j<=l;j++)
            {
                if(i==j)//相同直接初始化
                {
                    dp[i][j]=3-num[i];
                    continue;
                }
                dp[i][j]=n+n;//初始化最大,因为插入2n个一定能消完
                for(int k=i;k<j;k++)dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
                if((j-i)&1)//判断是否同色
                    continue;
                dp[i][j]=min(dp[i][j],dp[i+1][j-1]+(num[i]+num[j]==2));//两端都是1要加1
                if(num[i]+num[j]<4)//判断是否有一端是1
                {
                    for(int k=i+2;k<j;k+=2)//与两端同色的
                        if(num[k]==1)
                        dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k+1][j-1]);
                }
            }
        }
        printf("Case #%d: %d\n",cas,dp[1][l]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值