UVa 10700 - Camel trading

  题目大意:给一个不含括号、只有+和*运算的表达式,数字的范围在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] != '\0'; )
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] != '\0')   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] != '\0'; )
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] != '\0')   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.\n", lmax, lmin);
53     }
54     return 0;
55 }
View Code

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

 

转载于:https://www.cnblogs.com/xiaobaibuhei/p/3219657.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值