HDU 4403 A very hard Aoshu problem (DFS)

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

题意:  给定一个由数字组成的字符串,向里面加入一个等号,和任意个加号,使得等式成立,问一共有多少种方案。

思路:  枚举等号出现的位置,用equ表示,则1<=equ<=len-1,  也就是把等号加在第equ个数字后面,紧跟着第equ个数字。然后先DFS等号左边所有可能出现的情况,对应每个左边所出现的和lsum,再DFS等号右边所有可能出现的情况rsum,如果 rsum==lsum,那么有一种方案可行。

总结:通过DFS来搜出等号左边所有的状态,每一种状态压入栈中,然后从栈中取状态,再去DFS等号右边所有的状态,状态相等,则有一种方案可行。

#include <iostream>
#include <string.h>
using namespace std;
char str[20];
int val[20][20],ans,len;
void inite()
{
    memset(val,0,sizeof(val));
    for(int i=1;i<=len;i++)
        for(int j=i;j<=len;j++)
        {
            for(int k=i;k<=j;k++)
                val[i][j]=val[i][j]*10+(str[k]-'0');
        }
}
void DFSR(int lsum,int pos,int rsum)//dfs等号后边可能出现的情况
{
    if(pos>len)
    {
        if(lsum==rsum)
            ans++;
        return;
    }
    for(int k=pos;k<=len;k++)//注意是<=,因为最后一位也属于等号后边
        DFSR(lsum,k+1,rsum+val[pos][k]);//注意是k+1
}
void DFSL(int equ,int pos,int lsum)//dfs等号左边可能出现的情况,每种情况对应一个lsum(等号左边的和)
{
    if(pos>equ)//当等号左边的数字的位置大于等号的位置时,搜索等号后边
        DFSR(lsum,equ+1,0);
    for(int k=pos;k<=equ;k++)//注意是<=,equ代表的是等号加在第equ个数字后面
        DFSL(equ,k+1,lsum+val[pos][k]);
}
int main()
{
    while(cin>>(str+1)&&str[1]!='E')
    {
        ans=0;
        len=strlen(str+1);
        inite();
        for(int equ=1;equ<=len-1;equ++)
           DFSL(equ,1,0);
        cout<<ans<<endl;
    }
    return 0;
}


转载于:https://www.cnblogs.com/MisdomTianYa/p/6581719.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值