搜索:迭代深搜即可
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;
}