首页 > 其他 > 详细

ABC 045 C - Many Formulas

时间:2021-04-03 09:21:01      阅读:53      评论:0      收藏:0      [点我收藏+]

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.

 

这题只要枚举加号的位置就行。不过我用的是dfs,将每两个数之间设想有一个空格,可以讨论此处是否有加号。

代码如下:

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <string>
 6 #include <cstring>
 7 #include <vector>
 8 #define ll long long
 9 using namespace std;
10 bool flag[10];
11 char s[10];
12 ll ans;
13 int n;
14 void dfs(int k, ll sum, ll temp)//k指从左至右的第(k+1)个空隙
15 {
16     if (k == n - 1)
17     {
18         ans += (sum + temp );
19         
20         //ans += (sum + 10 * temp + s[k] - ‘0‘);
21         return;
22     }
23     dfs(k + 1, sum, 10 * temp + s[k + 1] - 0);
24     dfs(k + 1, sum + temp, s[k + 1] - 0);
25 }
26 int main()
27 {
28     char c;
29     while ((c = getchar()) != \n&&c != EOF)
30     {
31         s[n] = c;
32         n++;
33     }
34     dfs(0, 0, s[0] - 0);
35     cout << ans;
36     return 0;
37 }

 

尽管简单,但这题给了我一个教训:一定要把程序中涉及的可能越界的变量都考虑一遍。把ans设成long long,这我一开始就想到了。然而,递归函数参数的sum与temp我一开始设成了int,而这两者的错误会影响到最终的结果ans。

 

ABC 045 C - Many Formulas

原文:https://www.cnblogs.com/yangyi2120/p/14612837.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!