hdu2266How Many Equations Can You Find dfs深搜

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

思路:

一种是模拟,在每个位置选择插入加减符号或者不插入,dfs搜,搜到底层就计算一下插入的结果

另一种是直接搜,从每个位置开始都搜一遍(相比来说这种更简单也更省时)

代码:

模拟搜法:

#include
using namespace std;
#define ll long long
char num[20];
int sym[20];//1为+,2为-,0为空
ll m,ans = 0,len;
ll solve()
{
    ll bol = 1,cnt = 0,now = 0;
    for (int i = 1;i <= len;i ++)
    {
        now = now * 10 + (num[i - 1] - '0');
        if (sym[i])
        {
            if (bol == 1) cnt += now;
            else cnt -= now;
            bol = sym[i];
            now = 0;
        }
    }
    if (bol == 1) cnt += now;
    else cnt -= now;
    return cnt;
}
void dfs(ll index)
{
    if (index == len)
    {
        if (solve() == m) ans ++;
        return ;
    }
    sym[index] = 1;
    dfs(index + 1);
    sym[index] = 2;
    dfs(index + 1);
    sym[index] = 0;
    dfs(index + 1);
}
int main()
{
    while (~scanf("%s %lld",num,&m))
    {
        ans = 0;
        len = strlen(num);
        for (int i = 0;i < 20;i ++) sym[i] = 0;
        dfs(1);
        printf("%lld\n",ans);
    }
    return 0;
}

每个位置都搜一遍:

#include
using namespace std;
#define ll long long
char num[20];
ll m,ans,len;
void dfs(ll index,ll cnt)
{
    if (index == len)
    {
        if (cnt == m) ans ++;
        return ;
    }
    ll now = 0;
    for (ll i = index;i < len;i ++)
    {
        now = now * 10 + num[i] - '0';
        dfs(i + 1,cnt + now);
        if (index) dfs(i + 1,cnt - now);
    }
}
int main()
{
    while (~scanf("%s %lld",num,&m))
    {
        len = strlen(num);
        ans = 0;
        dfs(0,0);
        printf("%lld\n",ans);
    }
    return 0;
}

 

你可能感兴趣的:(dfs深搜)