• UVa 10700


      题目大意:给一个不含括号、只有+和*运算的表达式,数字的范围在1到20之间,算出计算结果的可能最大值和最小值。

      贪心,如果加法优先级比乘法高,那么得出的结果为最大值。(a+b)*c = a*c + b*c >= a+b*c。同理,如果乘法优先级比加法高,得出的结果为最小值。

     1 #include <cstdio>
     2 #include <cctype>
     3 
     4 int main()
     5 {
     6 #ifdef LOCAL
     7     freopen("in", "r", stdin);
     8 #endif
     9     double lmin, lmax, lstack[30];
    10     int top;
    11     int N;
    12     scanf("%d", &N);
    13     getchar();
    14     char s[100];
    15     while (N--)
    16     {
    17         gets(s);
    18         char ch = '+';
    19         top = 0;
    20         for (int i = 0; s[i] != ''; )
    21         {
    22             int n = 0;
    23             while (isdigit(s[i]))
    24             {
    25                 n = n*10 + s[i]-'0';
    26                 i++;
    27             }
    28             if (ch == '+')   lstack[top++] = n;
    29             else lstack[top-1] *= n;
    30             if (s[i] != '')   ch = s[i++];
    31         }
    32         lmin = 0;
    33         for (int i = 0; i < top; i++)
    34             lmin += lstack[i];
    35         top = 0;
    36         ch = '*';
    37         for (int i = 0; s[i] != ''; )
    38         {
    39             int n = 0;
    40             while (isdigit(s[i]))
    41             {
    42                 n = n*10 + s[i]-'0';
    43                 i++;
    44             }
    45             if (ch == '*')   lstack[top++] = n;
    46             else lstack[top-1] += n;
    47             if (s[i] != '')   ch = s[i++];
    48         }
    49         lmax = 1;
    50         for (int i = 0; i < top; i++)
    51             lmax *= lstack[i];
    52         printf("The maximum and minimum are %.0lf and %.0lf.
    ", lmax, lmin);
    53     }
    54     return 0;
    55 }
    View Code

      也可以用动态规划,不过觉得可以用贪心就不想麻烦了。

  • 相关阅读:
    MongoDB学习(1)—在Windows系统中安装MongoDB
    在windows系统的文件右键菜单中增加“命令提示符”
    python基础五之字典
    python基础四之列表
    python基础三之字符串
    python基础二
    python基础一
    二叉搜索树与双向链表
    记录一下Comparator的用法
    根节点到叶子节点路径之和为target
  • 原文地址:https://www.cnblogs.com/xiaobaibuhei/p/3219657.html
Copyright © 2020-2023  润新知