1. 程式人生 > >2266 How Many Equations Can You Find

2266 How Many Equations Can You Find

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

題目大意:給一個由0-9組成的字串和一個數字N,在任意兩個字元直接新增-或者+,是這組數的結果和為N,輸出一共有多少種方案 

解題思路:dfs來做,兩個字元之間可以新增符號的情況有三種,-,+,什麼也不加,當連續幾個字元之間沒有新增+或-時,這連續幾個字元的數值大小可以用下面的程式碼求解

int sum=0;
for(int i=0;i<len;i++)//len表示字串的長度
{
	sum=sum*10+str[i]-'0';
}

解決這個問題使用dfs求解就簡單多了,直接暴力列舉所有的情況, 我們從第一個字元開始,在這個字元後面加+或-或者什麼也不加,使用ans來記錄當前的結果,當走到最後一個字元,並且ans==N時,就讓sum++,最後輸出sum即可,

AC程式碼:

#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
char str[50];
int len;
ll sum,N;
void dfs(int k,ll ans)//k表示當前第幾位字元,ans表示前k位數字通過新增+或-得到的值 
{
	if(k==len)
	{
		if(ans==N)
		{
			sum++;
		}
		return ;
	}
	ll x=0; 
	for(int i=k;i<len;i++)
	{
		x=x*10+str[i]-'0';//用x表示從第k位到第i位數字之間不加+或-的數值大小  
		dfs(i+1,ans+x);//在第i位數字後加 +; 
		if(k!=0)//第一位數字前面不能加 -;  
			dfs(i+1,ans-x);//在第i位數字後加 -; 
	}
} 
int main()
{
	while(cin>>str)
	{
		len=strlen(str);
		sum=0;
		cin>>N;
		dfs(0,0);
		cout<<sum<<endl;
	}
	return 0;
}