首页 > 搜索 > DFS搜索 > HDU 4403-A very hard Aoshu problem-DFS-[解题报告]HOJ
2015
05-24

HDU 4403-A very hard Aoshu problem-DFS-[解题报告]HOJ

A very hard Aoshu problem

问题描述 :

Aoshu is very popular among primary school students. It is mathematics, but much harder than ordinary mathematics for primary school students. Teacher Liu is an Aoshu teacher. He just comes out with a problem to test his students:

Given a serial of digits, you must put a ‘=’ and none or some ‘+’ between these digits and make an equation. Please find out how many equations you can get. For example, if the digits serial is "1212", you can get 2 equations, they are "12=12" and "1+2=1+2". Please note that the digits only include 1 to 9, and every ‘+’ must have a digit on its left side and right side. For example, "+12=12", and "1++1=2" are illegal. Please note that "1+11=12" and "11+1=12" are different equations.

输入:

There are several test cases. Each test case is a digit serial in a line. The length of a serial is at least 2 and no more than 15. The input ends with a line of "END".

输出:

There are several test cases. Each test case is a digit serial in a line. The length of a serial is at least 2 and no more than 15. The input ends with a line of "END".

样例输入:

1212
12345666
1235
END

样例输出:

2
2
0

题目大意:

给定n个数字,用一个“=”和若干“+”能组成多少种等式

题目分析:

n很小,可以考虑爆搜。但是不好写,因为没想到做预处理,将能构成的所有数先保存,然后直接爆搜。当然,还是可以剪枝的。

下面是代码:

#include <iostream>
#include <string>
using namespace std;
const int maxn = 15;
string str;
int num[maxn][maxn];
int ans;
int len;

void get_num(int n)
{
    for(int i = 0; i < n; i++)
    {
        int temp = 0;
        for(int j = i; j < n; j++)
        {
            temp += str[j] - '0';
            num[i][j] = temp;
            temp *= 10;
        }
    }
}
void dfs_right(int s,int A,int sum,int len)
{
    if(s == len )
    {
        if(A == sum)
        {
            ans++;
            return ;
        }
    }
    if(A < sum) return ;
    for(int i = s; i < len; i++)
    {
        dfs_right(i+1,A,sum+num[s][i],len);
    }
}
void dfs_left(int s,int sum,int mid)
{
    if(s == mid)
    {
        dfs_right(mid,sum,0,len);
    }
    for(int i = s; i < mid; i++)
    {
        dfs_left(i+1,sum+num[s][i],mid);
    }
}
void print_num()
{
    for(int i = 0; i < len; i++)
    {
        for(int j = 0; j < len; j++) cout<<num[i][j]<<" ";
        cout<<endl;
    }
}
int main()
{
    while(cin>>str)
    {
        if(str[0] == 'E') break;
        len = str.size();
        get_num(len);
        //print_num();
        ans = 0;
        for(int i = 0; i < len-1; i++) dfs_left(0,0,i+1);
        cout<<ans<<endl;
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

参考:http://blog.csdn.net/mr_zys/article/details/11013119


,