A very hard Aoshu problem

本文介绍了一道复杂的奥数题目,该题目要求在给定的一串数字中插入‘+’号和一个‘=’号来形成尽可能多的有效等式。通过使用递归深度优先搜索的方法遍历所有可能的等式组合,并利用哈希映射记录等式的左侧和右侧表达式的值,从而高效地解决了这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D - A very hard Aoshu problem
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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 <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>

using namespace std;
#define N 20

char s[N];
int a[N], len;
map<int, int>ml, mr;

void dfs(int pos, int x, int v, int res, map<int, int> &m)
{
    if(pos == x)
    {
        int val = res + v * 10 + a[pos];
        m[val]++;
        return ;
    }
    dfs(pos + 1, x, 0, res + v * 10 + a[pos], m);
    dfs(pos + 1, x, v * 10 + a[pos], res, m);
}

int solve(int x)
{
    int res = 0;
    ml.clear();
    mr.clear();
    dfs(0, x, 0, 0, ml);
    dfs(x + 1, len - 1, 0, 0, mr);
    for(map<int, int>::iterator it = ml.begin(); it != ml.end(); it++)
        res += (it->second) * mr[(it->first)];

    return res;
}

int main()
{
    while(~scanf("%s", s) && s[0] != 'E')
    {
        int ans = 0;
        len = strlen(s);
        for(int i = 0; i < len; i++) a[i] = s[i] - '0';
        for(int i = 0; i < len - 1; i++)
            ans += solve(i);
        printf("%d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值