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

HDU 2266 How Many Equations Can You Find(DFS)

时间:2015-07-06 17:34:29      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

HDU 2266 How Many Equations Can You Find(DFS)

标签:

原文地址:http://www.cnblogs.com/I-love-HLD/p/4624846.html

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