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

A very hard Aoshu problem

时间:2016-08-31 11:49:25      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

 

 

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

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

#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

标签:

原文地址:http://www.cnblogs.com/iwantstrong/p/5825243.html

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