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
and9
, 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
125
Sample Output 1
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.
Sample Input 2
9999999999
Sample Output 2
12656242944
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.
就是给一个数字字符串,然后在字符串中添加“ + ”把所有情况的 和 加和的结果;#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;
}