杭电2266 How Many Equations Can You FindDFS

Posted 唐唐123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了杭电2266 How Many Equations Can You FindDFS相关的知识,希望对你有一定的参考价值。

How Many Equations Can You Find

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 892    Accepted Submission(s): 590


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
 
Author
dandelion
 
Source
 
Recommend
lcy
 
 
AC代码:
 1 #include<cstring>
 2 #include<cstdio>
 3 using namespace std;
 4 #define LL long long
 5 LL num,n,len;
 6 char str[15];
 7 void DFS(LL x, LL sum)
 8 {//x是取的字符串的长度, sum是当前的值 
 9     if(x == len)//当取得字符串长度==字符串总串长度时 
10     {
11         if(sum==n)//当前结果== n时 
12             num++;
13         return ;  
14     }
15     LL k=0;//核心的东东  短短的几句  却是指数级的搜索量啊
16     for(int i=x;i<len;i++)//这里刚开始写成了从0开始,哎合适能搜到头啊
17     {
18         k=k*10+str[i]-0;
19         
20         //加减两种可能 
21         DFS(i+1, sum+k);
22         if(x != 0)//第一个数字前不能加“-”号
23             DFS(i+1, sum-k);
24     }
25 }
26 int main()
27 {
28     while(scanf("%s %lld",str,&n)!=EOF)
29     {
30         len=strlen(str);
31         num = 0;
32         DFS(0,0);
33         printf("%lld\n", num);
34     }
35     return 0;
36 }

以上是关于杭电2266 How Many Equations Can You FindDFS的主要内容,如果未能解决你的问题,请参考以下文章

hdu 1316 How Many Fibs?

P - How many

HDOJ 1316 How Many Fibs?

LightOJ - 1140 How Many Zeroes?

how many tables

How Many Tables HDU - 1213