D - 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
把这道题贴出来的意思就是很玄学,我的代码连样例都没有过竟然AC了,我也是服,而且比网上的标程还要快
code

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
const int maxn = 100;

char str[maxn];
ll val,len,ans;

void dfs(ll sum,ll per,int pos) {
    if ( len == pos ) {
        sum += per;
        if(sum == val){
            ans++;
        }
        return;
    }
    for (int i = 0;i<3;i++) {
        if ( i == 0 ) {
            if (per>=0) { 
                dfs(sum,per*10+1LL*(str[pos]-'0'),pos+1);
            } else if (per<0) {
                dfs(sum,per*10-1LL*(str[pos]-'0'),pos+1);
            }
        } else if (i == 1) {
            dfs(sum+per,1LL*(str[pos]-'0'),pos+1);
        } else if (i == 2) {
            dfs(sum+per,-1LL*(str[pos]-'0'),pos+1);
        }
    }
}

int main() {
    while(~scanf("%s %lld",str,&val))
    {
        ans = 0;
        len = strlen(str);
        dfs(0,1LL*(str[0]-'0'),1);
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2018-08-01 22:31  Nlifea  阅读(134)  评论(0编辑  收藏  举报