Title: 10700-camel Trading
The main topic: give some expressions, the expression is composed of numbers and plus multiplication sign, the number range "1,20". These expressions may be missing parentheses, asking for the maximum and minimum values that can be obtained after the expression is added in parentheses.
The idea of solving problems: Because these numbers are all positive integers, we can use greed. Otherwise we can see that the maximum value is to do the multiplication first, and the minimum is to do the multiplication first. Note that the value here is going to be a long long because the values of the expression may exceed int.
Code:
#include <stdio.h> #include <string.h>const int N = 15;char Op[n];char str[3 * N];long long Num[n];long long CA Culate_max (int count) {Long long temp[n];for (int i = 0; i < count; i++) Temp[i] = num[i];for (int i = count-2; I ; = 0; i--) if (op[i] = = ' + ') {Temp[i] + temp[i + 1];temp[i + 1] = Temp[i];} Long Long sum = temp[0];for (int i = 0; i < count-1; i++) {if (op[i] = = ' * ') sum *= temp[i + 1];} return sum;} Long long caculate_min (int count) {Long long temp[n];for (int i = 0; i < count; i++) Temp[i] = num[i];for (int i = Coun T-2; I >= 0; i--) {if (op[i] = = ' * ') temp[i] = temp[i] * temp[i + 1];} Long Long sum = temp[0];for (int i = 0; I <= count-2; i++) {if (op[i] = = ' + ') sum + = Temp[i + 1];} return sum;} int init () {int t = 0;long long sum;scanf ("%s", str), for (int i = 0; i < strlen (str); i++) {if (str[i] = = ' + ' | | str [i] = = ' * ') op[t++] = str[i];else {sum = 0;while (str[i] >= ' 0 ' && str[i] <= ' 9 ') {sum = sum * + str[i]- ' 0 '; i++;} num[T] = sum;i--;}} return T + 1;} int main () {int t;int count;scanf ("%d", &t), while (t--) {count = init ();p rintf ("The maximum and minimum is%lld an D%lld.\n ", Caculate_max (count), Caculate_min (count));} return 0;}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Uva:10700-camel Trading (Greed)