Atcoder 045 -二进制枚举

C - たくさんの数式 / Many Formulas


Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

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.

Input

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

S

Output

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


Sample Input 1

Copy
125

Sample Output 1

Copy
176

There are 4 formulas that can be obtained: 1251+2512+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.


Sample Input 2

Copy
9999999999

Sample Output 2

Copy
12656242944
题意很明确 :

There are 4 formulas that can be obtained: 1251+2512+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.

就是给一个数字字符串,然后在字符串中添加“ + ”把所有情况的  和 加和的结果;

二进制枚举 "+" 位置,字符串最多10位,总共也就2^9 种情况,然后简单操作一下求加上“+” 后的和即可

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
char s[15];
int pos[15];
LL num(int l,int r)
{
    LL ans=0;
    //cout<<l<<" "<<r<<endl;
    for(int i=l;i<=r;i++)
    {
        ans=ans*10+s[i]-'0';
    }
    return ans;
}
LL solve(int n)
{
    int l=-1,r=0;
    LL ans=0;
    pos[n]=1;
    for(int i=0;i<=n;i++)
    {
        if(pos[i]==0)
            r++;
        else
        {
            ans+=num(l+1,i);
            l=i;
        }
    }
    return ans;
}
int main()
{
     while(cin>>s)
     {
         int n=strlen(s);
         long long ans=0;
         int R= (1<<(n-1))-1 ;
        // cout<<R<<endl;
        for(int i=0;i<=R;i++)
        {
            memset(pos,0,sizeof(pos));
            int tot=0;
            int temp=i;
            while(temp)
            {
                pos[tot++]=temp%2;
                temp=temp/2;
            }
            //cout<<solve(n-1)<<endl;
            ans+=solve(n-1);
            //cout<<ans<<endl;
        }
        printf("%lld\n",ans);
     }
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值