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): 1740    Accepted Submission(s): 1197


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
 


题意:用一个等号'='将一串数字分为两份,每部分中的任意两个数字中都可以插入'+'号,求一共有多少种组合使得等式成立


思路:对等号的每一个位置DFS左端所有情况 然后在每种情况继续遍历等号右端所有情况


#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#define LL long long
using namespace std;
char s[20];
int num[20],len;
LL ans,mx;
//右侧等式DFS加号
void dfs2(int x,int ed,int sum,int su,int lsum){
    if(sum+su>lsum) return;
    if(x==ed+1){
        if(sum+su==lsum)
            ans++;
        return;
    }
    dfs2(x+1,ed,sum,su*10+num[x],lsum);
    dfs2(x+1,ed,sum+su,num[x],lsum);
}
//左侧等式DFS+号
void dfs(int x,int ed,int sum,int su){
    if(sum+su>mx) return;
    if(x==ed+1){
        dfs2(x+1, len-1, 0, num[x], sum+su);
        return;
    }
    dfs(x+1,ed,sum,su*10+num[x]);//选择不放+
    dfs(x+1,ed,sum+su,num[x]);//放+ 该段已经结束 su加入sum
}

int main()
{
    while(scanf("%s",s)){
        if(!strcmp(s, "END")) break;
        ans = 0;
        len = (int)strlen(s);
        for(int i=0;i<len;i++) num[i] = s[i] - '0';
        for(int i=0;i<len-1;i++){
            mx = 0;
            for(int j=i+1;j<len;j++){
                mx = mx*10 + num[j];
            }
            dfs(1,i,0,num[0]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值