问题 : Many Formulas

题目描述

You are given a string S consisting of digits between 1 and 9, inclusive. You can insert the letter + into some of the positions (possibly none) between two letters in this string. Here, + must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.

Constraints
1≤|S|≤10
All letters in S are digits between 1 and 9, inclusive.

输入

The input is given from Standard Input in the following format:
S

输出

Print the sum of the evaluated value over all possible formulas.

样例输入 Copy
125
样例输出 Copy
176
提示

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125
1+25=26
12+5=17
1+2+5=8
Thus, the sum is 125+26+17+8=176.

这个题毫无疑问是可以用DFS做的

这里我们可以考虑一下,这个题我们可以看作是设置断点的问题,断点将前后两个数分开,并求加和,所以我们只要判断从第一个数到倒数第二个数是否设置断点(最后一个数后面没数据,是否设置断点无意义了),即0/1问题

这里我们可以直接压位做

代码实现:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

char s[11];
//存储数据

int main()
{
	scanf("%s", &s);
	ll len = strlen(s);
	ll elerm, sum = 0;
	//elerm表示断开而成的每一个数,sum表示最后所有elerm的加和结果
	ll tot = 1 << (len - 1);
	//tot表示一共有多少种断点设置方法(注:最后一位不需要)
	//一共是len位,每位都有0/1两种,所以一共有(1<<(len-1))种

	//以下的代码,所有的数据都是二进制的方式进行处理的,0表示不设置断点,1表示设置断点
	for (ll i = 0; i < tot; i++)
	//对所有断点设置方法进行检验
	{
		elerm = s[0] - '0';
		//初始值(因为无论怎么设置断点,第一个值是都要进入到elerm中)
		for (int j = 0; j < len; j++)
		//j现在对第j位的断点状态进行检验
		{
			if (j == len - 1 || i & (1 << j))
			//j==len-1表示j现在检测到了最后一位,后面没数据了,自动设置断点并退出
			//i & (1 << j)表示对i(二进制形式)的第j位进行检验,看这一位是否设置了断点
			{
				sum = sum + elerm;
				elerm = 0;
				//如果设了断点,则此数加到sum中,并初始化
				if (j == len - 1)break;
			}
			elerm = elerm * 10 + (s[j + 1] - '0');
			//表示这一位没设置断点,则elerm将下一位包含进来
		}
	}

	cout << sum;
	//sum将所有方法的所有elerm都加和了,可以输出了
}
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值