Camel tradingtime limit: 1 second
Background
Aroud 800. D ., el mamum, calif of Baghdad was presented the Formula 1 + 2*3*4 + 5, which had its origin in the financial accounts of a camel transaction. the formula lacked parenthesis and was ambiguous. so, he decided to ask savants to provide him with a method to find which interpretation is the most advantageous for him, depending on whether is buying or selling the camels.
The Problem
You are commissioned by El mamum to write a program that determines the maximum and minimum possible interpretation of a parenthesis-less expression.
Input
The input consists of an integerN, FollowedNLines, each containing an expression. Each expression is composed of at most12Numbers, each ranging1And20, And separated by the sum and product Operators+And*.
Output
For each given expression, the output will echo a line with the corresponding maximal and minimal interpretations, following the format given in the sample output.
Sample Input
31+2*3*4+54*18+14+7*103+11+4*1*13*12*8+3*3+8
Sample output
The maximum and minimum are 81 and 30.The maximum and minimum are 1560 and 156.The maximum and minimum are 339768 and 5023.
Question:
Calculate the maximum and minimum values of a formula under different combinations.
Solution:
The maximum value is calculated first by addition and then by multiplication. The minimum value is calculated first by multiplication and then by addition.
Code:
# Include <iostream> # include <cstdio> # include <vector> # include <sstream> using namespace STD; int N; vector <long> vmini, vmaxi; string STR; void solve () {long Mina, maxa, A, B, maximum = 1, minimum = 0; stringstream SS; char ch; CIN> STR; SS <STR; SS> A; // The stream can only be placed in front. mina = maxa = A; vmaxi. push_back (maxa); vmini. push_back (Mina); While (SS> CH> B) {If (CH = '+') {maxa = vmaxi. back () + B; vmaxi. pop_back (); vmaxi. push_back (maxa); vmini. push_back (B);} else {Mina = vmini. back () * B; vmini. pop_back (); vmini. push_back (Mina); vmaxi. push_back (B) ;}}for (INT I = 0; I <vmaxi. size (); I ++) {// This makes traversing easier. maximum = maximum * vmaxi [I];} For (INT I = 0; I <vmini. size (); I ++) {minimum = Minimum + vmini [I];} printf ("the maximum and minimum are % LLD and % LLD. \ n ", maximum, minimum) ;}int main () {scanf (" % d ", & N); For (INT I = 0; I <N; I ++) {vmaxi. clear (); vmini. clear (); solve ();} return 0 ;}