首页 > 代码库 > A very hard Aoshu problem

A very hard Aoshu 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

1212123456661235END

Sample Output

220

 

 

 

 

【题意】添加加号和等号后成为一个合法的等式,问这样的等式有多少个

【思路】爆搜,检验左右的值之和是否相同

#include<iostream>#include<string.h>#include<string>#include<stdio.h>using namespace std;const int N=20;int num[N][N];string str;int ans;int len;void getnum()//打表,从i到j的数相加之和用num数组保存{    for(int i=0;i<len;i++)    {        int tmp=0;        for(int j=i;j<len;j++)        {            tmp+=str[j]-0;            num[i][j]=tmp;            tmp*=10;        }    }}void dfsright(int s,int tar,int sum)//等号右边搜索{    if(s==len)//只有当刚好扫到最后且此时右边的值等于左边    {        if(tar==sum)        {ans++;return;}    }    if(tar<sum) return;//右边当前已经大于左边就没必要继续搜索了,返回    for(int i=s;i<len;i++)    {        dfsright(i+1,tar,sum+num[s][i]);    }}void dfsleft(int s,int sum,int mid)//左边搜索{     if(s==mid)//当扫到mid时,说明等号左边已经加完了,进入右边        dfsright(mid,sum,0);    for(int i=s;i<mid;i++)    {        dfsleft(i+1,sum+num[s][i],mid);    }}int main(){    while(cin>>str)    {        if(str[0]==E) break;        len=str.size();        getnum();        ans=0;        for(int i=0;i<len-1;i++)        {            dfsleft(0,0,i+1);        }        cout<<ans<<endl;    }    return 0;}

 

A very hard Aoshu problem