问题描述
现在给出一个只包含0、1、2、3、4、5、6、7、8、9的字符串。要求您在字符之间添加“+”或“-”符号。就像给你一个字符串“12345”,你可以算出一个字符串“123+4-5”。现在给你一个整数N,请告诉我你能找到多少种方法使字符串的结果等于N,你最多只能在两个相邻的字符中选择一个符号。
输入
每种情况都包含一个字符串s和一个数字N。您可以确保字符串的长度不会超过12,并且N的绝对值不会超过9999999999。
输出
输出包含每个数据集的一行:可以找到的生成方程的方法的数量。
Sample Input
123456789 3
21 1
Sample Output
18
1
分析:
马上能想到的是枚举和搜索。
题目数据最大12位,枚举显然不行。
那么dfs罢。
code:
#include<iostream>
#include<cstdio>
typedef long long ll;
const int inf=0x3f3f3f3f;
const int inn=0x80808080;
using namespace std;
string a;
ll n;
ll ans;
ll len;
void dfs(ll num,ll now){
if(now==len){
if(num==n){
ans++;
}
return ;
}
ll temp=0;//很关键
for(ll i=now;i<len;i++){//这个循环很猛
temp=temp*10+a[i]-'0';
dfs(num+temp,i+1);
if(now){//第一个数字前不能加负号
dfs(num-temp,i+1);
}
}
}
int main(){
while(cin>>a>>n){
len=a.size();
ans=0;
dfs(0,0);
cout<<ans<<endl;
}
return 0;
}