1. 程式人生 > >hdu 4403 A very hard Aoshu problem(dfs)

hdu 4403 A very hard Aoshu problem(dfs)

【題目】

A very hard Aoshu problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1852    Accepted Submission(s): 1278  

Problem Description

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.

 

Input

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".

 

Output

For each test case , output a integer in a line, indicating the number of equations you can get.

 

Sample Input

1212

12345666

1235

END

Sample Output

2

2

0

Source

【題意】

加入任意個‘+’與一個‘=’使字串成為合法的等式有多少種方法。

【思路】

先處理出第i個位置到第j個位置的數sum[i][j],然後遍歷嘗試每一種放等號的可能情況,搜尋一下左右兩邊放置加號的所有可能情況,並判斷計數等式成立的方法數。

【程式碼】

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#define go(i,a,b) for(int i=a;i<=b;i++)
#define og(i,a,b) for(int i=a;i>=b;i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define Pi acos(-1)
#define eps 1e-8
using namespace std;
typedef long long int ll;
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
int sum[20][20],ans;
string a;
void dfs2(int add1,int add2,int l)
{
    if(add1<add2) return;
    if(add1==add2&&l==a.size())
    {
        ans++;
        return;
    }
    for(int i=l+1;i<=a.size();i++)
        dfs2(add1,add2+sum[l][i-1],i);
}
void dfs1(int add1,int l,int r)
{
    if(l==r)
    {
        dfs2(add1,0,r);
        return;
    }
    for(int i=l+1;i<=r;i++)
        dfs1(add1+sum[l][i-1],i,r);
}
main()
{
    while(cin>>a)
    {
        if(a=="END") break;
        int l=a.size();
        for(int i=0;i<l;i++)
        {
            int t=a[i]-'0';
            sum[i][i]=t;
            for(int j=i+1;j<l;j++)
            {
                t=t*10+a[j]-'0';
                sum[i][j]=t;
            }
        }
        ans=0;
        for(int i=1;i<l;i++)
            dfs1(0,0,i);
        printf("%d\n",ans);
    }
}