How Many Equations Can You Find
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 714 Accepted Submission(s): 467
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的方法数,深搜;
代码:
1 #include<stdio.h> 2 #include<string.h> 3 __int64 ans,N; 4 int len; 5 char s[15]; 6 void dfs(int t,__int64 sum){ 7 if(t==len){ 8 //printf("%I64d\n",sum); 9 if(sum==N)ans++; 10 return; 11 } 12 __int64 k=0; 13 for(int i=t;i<len;i++){ 14 k=k*10+s[i]-‘0‘; 15 dfs(i+1,sum+k); 16 if(t!=0)dfs(i+1,sum-k); 17 } 18 } 19 int main(){ 20 while(~scanf("%s%I64d",s,&N)){ 21 len=strlen(s); 22 ans=0; 23 dfs(0,0); 24 printf("%I64d\n",ans); 25 } 26 return 0; 27 } 28 /*#include<stdio.h> 29 #include<string.h> 30 __int64 ans,N; 31 int len; 32 char s[15]; 33 void dfs(int top,__int64 sum){ 34 if(top==len){//写成N了错的心酸。。。 35 //printf("%I64d %d\n",sum,len); 36 if(sum==N)ans++; 37 return ; 38 } 39 __int64 x=0; 40 for(int i=top;i<len;i++){ 41 x=x*10+s[i]-‘0‘; 42 dfs(i+1,sum+x); 43 if(top!=0)dfs(i+1,sum-x); 44 } 45 } 46 int main(){ 47 while(~scanf("%s%I64d",s,&N)){ 48 len=strlen(s); 49 //printf("%d\n",len); 50 ans=0; 51 dfs(0,0); 52 printf("%I64d\n",ans); 53 } 54 return 0; 55 }*/