码迷,mamicode.com
首页 > 其他好文 > 详细

杭电2266 How Many Equations Can You Find【DFS】

时间:2016-10-06 19:28:06      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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 Find【DFS】

标签:

原文地址:http://www.cnblogs.com/123tang/p/5934123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!