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 12numbers, 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.
给你一个计算表达式(只有 + 和 *),它的最小值就是普通的计算,先算* ,再算+ ,所以样例1的结果为1+24+5=30
最大值为先计算+,再算*,样例1为(1+2)*3*(4*5)=3*3*9=81
直接数组加标记就过了,用栈写的应该会更简单点。。。
#include <iostream> #include <cstdio> #include <cstring> #include <stdlib.h> #include <algorithm> #include <cmath> #define MAX 0x3f3f3f3f #define N 100 using namespace std; long long int a[N]; long long int c[N]; long long int num,mans,kans; char s[N]; void minans() { bool b[N]; memset(b,false,sizeof(b)); //标记a中的数值或运算符是否访问过 for(int i=1; i<num; i++) { if(a[i]==-1) //找到'*',把前后的两个数字乘起来放在a[i+1],然后标记下a[i-1],a[i]; { if(a[i-1]>=1 && a[i+1]>=1) { b[i-1]=true; b[i]=true; a[i+1]=a[i+1]*a[i-1]; } } } //这个for结束后,a中的'*'全被标记 mans=0; for(int i=0; i<num; i++) //把a中所有剩下未被标记的数全部加起来就是最小值 { if(!b[i]&&a[i]!=-2) mans+=a[i]; } } void maxans() { bool b[N]; memset(b,false,sizeof(b)); for(int i=1; i<num; i++) //同求最小值,只不过先找到'+' { if(c[i]==-2) { if(c[i-1]>=1 && c[i+1]>=1) { b[i-1]=true; b[i]=true; c[i+1]=c[i+1]+c[i-1]; } } } kans=1; for(int i=0; i<num; i++) //把剩下的所有数乘起来为最大值 { if(!b[i]&&c[i]!=-1) kans*=c[i]; } } int main() { int T; scanf("%d",&T); while(T--) { scanf("%s",s); char len=strlen(s); num=0; for(int i=0; i<len; i++) //将每个数字和运算符按顺序取出来放到数组a中,'*'记为-1,'+'记为-2 { if(s[i]>='0' && s[i]<='9') { if(s[i+1]>='0' && s[i+1]<='9') { a[num++]=10*(s[i]-'0') + s[i+1]-'0'; i++; } else a[num++]=s[i]-'0'; } else { if(s[i]=='*') a[num++]=-1; else if(s[i]=='+') a[num++]=-2; } } for(int i=0; i<num; i++) //保存下a,方便下次求最大值 c[i]=a[i]; minans(); //最小值 maxans(); //最大值 printf("The maximum and minimum are %lld and %lld.\n",kans,mans); } return 0; }