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.

思路
二进制暴力,将插入加号的位置视为二进制的一位,当其为1时,将其视为‘+’号,否则则不插入

代码实现
string模拟法

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <string>
#include <cstring>
using namespace std;
typedef long long ll;
const int N=105;
string s;
int a[N];
ll ans;
ll getsum(string t)
{
    ll sum=0,tmp=0;
    for(int i=0;i<t.size();i++)
    {
        if(t[i]=='+')
        {
            sum+=tmp;
            tmp=0;
        }
        else tmp=tmp*10+t[i]-'0';
    }
    return sum+tmp;
}
int main()
{
    cin>>s;
    int l=s.size()-1;
    while(1)
    {
        string temp;
        for(int i=0;i<l;i++)
        {
            a[i+1]+=a[i]/2;
            a[i]%=2;
        }
        if(a[l]) break;
        for(int i=0;i<l;i++)
        {
            temp+=s[i];
            if(a[i]) temp+="+";
        }
        temp+=s[l];
        ans+=getsum(temp);
        a[0]++;
    }
    cout<<ans<<endl;
    return 0;
}

二进制实现

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <string>
#include <cstring>
using namespace std;
typedef long long ll;
const int N=105;
char s[N];
ll ans;
int main()
{
    scanf("%s",s);
    int l=strlen(s);
    int m=1<<(l-1);
    for(int i=0;i<m;i++)
    {
        ll t=s[0]-'0';
        for(int j=0;j<l;j++)
        {
            if(j==l-1 || i&1<<j) //当i&1<<j ==1 时 说明i的第j位 =1(二进制下)
            {
                ans+=t;
                t=0;
                if(j==l-1) break;
            }
            t=t*10+s[j+1]-'0';
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43935894/article/details/88095859