Problem E - Camel trading
Time Limit: 1 second
Background
Aroud 800 A.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 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 integer N, followed by N lines, each containing an expression. Each expression is composed of at most 12 numbers, each ranging between 1 and 20, 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
3 1+2*3*4+5 4*18+14+7*10 3+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.
description:
求只含有整数+和*的表达式的最大值和最小值。
分析:
最大值先算加法,最小值先算乘法。
代码:
#include #include #include #define N 50 long long max(char s[]) { int i, top, l, f, len; long long t, st_in[N]; top = 0; t = 0; f = 0; i = 0; len = strlen(s); while(i < len){ while(isdigit(s[i])){ t = t * 10 + s[i] - '0'; i++; } if(f == 1) st_in[top-1] += t; else st_in[top++] = t; f = 0; t = 0; if(s[i] == '+') f = 1; i++; } t = 1; while(top > 0){ t *= st_in[--top]; } return t; } long long min(char s[]) { int i, top, l, f, len; long long t, st_in[N]; top = 0; t = 0; f = 0; i = 0; len = strlen(s); while(i < len){ while(isdigit(s[i])){ t = t * 10 + s[i] - '0'; i++; } if(f == 1) st_in[top-1] *= t; else st_in[top++] = t; f = 0; t = 0; if(s[i] == '*') f = 1; i++; } t = 0; while(top > 0){ t += st_in[--top]; } return t; } int main() { char s[N]; int n; scanf("%d", &n); while(n-- > 0){ scanf("%s", s); printf("The maximum and minimum are %lld and %lld.\n", max(s), min(s)); } return 0; }