[bzoj2239] 猜谜 迭代深搜 or 动态规划

搜索:迭代深搜即可
dp:
+和*是两个不同的状态,如果一边考虑加,一边考虑乘,实在麻烦。
不如分开进行考虑。

#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

int T , n , Max_dep;
int num[25][25];
bool have_ans , have_zero[25] ;
string str;

void Dfs(int x , int pre , int now , int mut , int value)
{
    if(value > T || now > Max_dep || have_ans) return;
    if(x == n)
    {
        if(value + mut * num[pre][n] == T) have_ans = true;
        return;
    }

    if(value + mut > T && !have_zero[x-1]) return;
    Dfs(x+1 , pre , now , mut , value);
    Dfs(x+1 , x+1 , now+1 , 1 , value + mut * (num[pre][x]));
    Dfs(x+1 , x+1 , now+1 , mut * num[pre][x] , value);
}
void Prep()
{
    n = str.length();
    str = " " + str;
    memset(have_zero , false , sizeof have_zero);
    for(int i=n ; i>=1 ;i--)
        if(str[i] == '0')
            while(i--) have_zero[i] = true;
    for(int i=1;i<=n;i++)
    {
        int sum = 0;
        for(int j=i;j<=n;j++)
        {
            sum = sum * 10 + (str[j] - '0');
            num[i][j] = min(sum , T+1);
            sum = min(sum , T+1);
            /*防止爆炸*/ 
        }
    }
}

void Solve()
{
    int ans = -1 , L = 0 , R = n - 1;
    while(L <= R)
    {
        Max_dep = (L + R) >> 1;
        have_ans = false;
        Dfs(1 , 1 , 0 , 1 , 0);
        if(have_ans) ans = Max_dep , R = Max_dep - 1;
        else L = Max_dep + 1;
    }
    cout<< ans << endl;
}

int main()
{
    while(cin>>str>>T && T >= 0) 
    {
        Prep();
        Solve();    
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值