HDU - 4403 A very hard Aoshu problem ——dfs 数值符号插入

14 篇文章 0 订阅

A very hard Aoshu problem

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


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

题意:给定一串数字,向里面加‘+’和‘=’使得算式成立,问有几种可能的加法。


思路:先枚举所有等号出现的位置,每一种情况中从左侧开始搜索,搜出直到等号前所有可能出现的计算结果数值,然后从右侧搜索,每次搜到结尾就与第一次搜索中的数值比较,有出现就加上。其中记录计算结果的时候用map来计数。

dfs中t是搜索的类型,即是左侧搜还是右侧搜,关系到搜索到结尾时进行的操作类型。x是当前搜索到的位置,end是结束的位置,sum是结算到当前位置的总和,m是计算当前操作数的变量。我们要遍历所有的计算结果,路径有两条,一是把这个数直接放进m中,此时需要把m加到sum中,二是把这个数与原来的m结合。


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
#include <cmath>
#include <vector>
#define max_ 200010
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;

char sent[20];
char tmp[5]="END";
map<int,int>mp;
map<int,int>::iterator iter;
int ans;
void dfs(int t,int x,int end,int sum,int m)
{
    if(x==end)
    {
        sum+=m;
        if(t==1)
        {
            mp[sum]++;
        }
        else
        {
            if(sum!=0)
            ans+=mp[sum];
        }
        return;
    }
    dfs(t,x+1,end,sum+m,sent[x]-'0');
    dfs(t,x+1,end,sum,m*10+sent[x]-'0');
}
int main(int argc, char const *argv[]) {
    while(scanf(" %s",sent)!=EOF&&strcmp(sent,tmp))
    {
        int i,l=strlen(sent);
        ans=0;
        for(i=1;i<l;i++)
        {
            mp.clear();
            dfs(1,0,i,0,0);
            dfs(2,i,l,0,0);
        }
        printf("%d\n",ans/4 );
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值