HDU 2266 How Many Equations Can You Find(DFS)

How Many Equations Can You Find

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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,m.你需要在n的中间填上加号或减号,或者不填。让n这个部分的值等于m。问有多少种方案。

举个例子:n=12345.

你可以操作它,使它变成这样 123+4-5=122。

 

解题思路:

dfs,考虑已经处理的数字的个数和当前这部分的值,处理到终点时,如果等于m,结果+1.

 

代码:

#include<cstdio>

#include<cstring>

#define LL long long

using namespace std;

char String[120];

LL Equation;

int Length,Answer;

void Search_For_Answer(int Now_Position,LL Now_Value)

{

    if(Now_Position>=Length)

    {

        if(Now_Value==Equation) Answer++;

        return;

    }

    LL Temp_Value=0;

    for(int i=1;i<=Length-Now_Position;i++)

    {

        Temp_Value=Temp_Value*10+String[i-1+Now_Position]-'0';

        Search_For_Answer(Now_Position+i,Now_Value+Temp_Value);

        if(Now_Position)

            Search_For_Answer(Now_Position+i,Now_Value-Temp_Value);

    }

}

int main()

{

    while(scanf("%s%lld",String,&Equation)!=EOF)

    {

        Answer=0;

        Length=strlen(String);

        Search_For_Answer(0,0);

        printf("%d\n",Answer);

    }

    return 0;

}

你可能感兴趣的:(find)