Problem Description
Now give you an string which only contains 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9.You are asked to add the sign ‘+’ or ’-’ between the characters. Just like give you a string “12345”, you can work out a string “123+4-5”. Now give you an integer N, please tell me how many ways can you find to make the result of the string equal to N .You can only choose at most one sign between two adjacent characters.
Input
Each case contains a string s and a number N . You may be sure the length of the string will not exceed 12 and the absolute value of N will not exceed 999999999999.
Output
The output contains one line for each data set : the number of ways you can find to make the equation.
Sample Input
123456789 3
21 1
Sample Output
18
1
这题也是一个典型的深搜题,就是在前一个字符串中插入适当的+或-(当然:也可以不插任何运算符)使得最后运算结果能等于右边给定的整数n,要你找出所有情况的总数。
比如我在2跟1中间插一个 - 号就可以得到结果1, 并且只有这一种插法,所以最终我输出结果1。
这道题和前几天我刷的那个1539–Shredding Company很像,也是在数字串中插运算符最后得到指定结果,所以思路也非常显而易见了。
我的AC代码:
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 20;
char str[maxn];
int n, cnt, len;
//分割点取值范围:0---len - 1
void dfs(int pos, int sign, int sum)
{
if(pos == len)
{
if(sum == n)
cnt++;
return ;
}
int temp = 0;
for(int i = pos;i < len;i++) //注意:分割点只有+或-, 如果是连续的那么就不叫被分割
{
temp = temp * 10 + str[i] - '0';
if(i == len - 1)
dfs(i + 1, 1, sum + sign * temp); //这里不做特殊处理的话,最后结果就是两倍!
else
{
dfs(i + 1, 1, sum + sign * temp); //如果前一个的sign是-, 那么后面的就是sum - temp
dfs(i + 1, -1, sum + sign * temp);
//上面两句话完成后, i后面的所有情况相当于都遍历完了, 然后i++再枚举下一个分割点
}
}
}
int main()
{
while(~scanf("%s%d", &str, &n))
{
cnt = 0;
len = strlen(str);
dfs(0, 1, 0);
cout << cnt << endl;
}
return 0;
}
这里我用一个参数sign来区分加或减两种情况,写完之后又欣赏了下网上大牛的代码,写得确实比我简洁, 而且我也发现这个参数其实是没有必要的,只不过我的思考方式和他们的稍微有点差异,这里还是贴上我自己的原装代码。
这题输入的地方要注意一下,有点坑。平常习题我们写while(~scanf("%d", &n) != EOF)这种输入是绝对可以的,但这一题不知为什么,写了!= EOF就会TLE, 调试半天才发现是这个原因,我还以为是差剪枝语句,坑死了!