3.3——搜索 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.
样例输入
复制样例数据
125
样例输出
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.
来源/分类
ps:有点不好理解。对递归理解应该加深
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
int a[15],x;
ll ans;
void dfs(int p,ll sum){//p表示位置
if(p==x) {
ans+=sum;
//cout<<"ans="<<ans<<endl;
return;
}
ll t=0;
cout<<t<<endl;
for(int i=p;i<x;i++){//枚举每个位置,在看下一个位置,不能取+号返回。根据递归,可以得到所有情况。
t=t*10+a[i];
//cout<<t<<endl;
dfs(i+1,sum+t);
}
}
int main()
{
ll s;
scanf("%lld",&s);
while(s){
int b=s%10;
a[x++]=b;
s/=10;
}
reverse(a,a+x);
dfs(0,0);
cout<<ans<<endl;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步