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.
You are commissioned by El Mamum to write a program that determines the maximum and minimum possible interpretation of a parenthesis-less expression.
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 *.
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.
3 1+2*3*4+5 4*18+14+7*10 3+11+4*1*13*12*8+3*3+8
The maximum and minimum are 81 and 30. The maximum and minimum are 1560 and 156. The maximum and minimum are 339768 and 5023.
题意:给你一个没有括号的表达式,只有数字和加乘号,怎么样组合使它最大最小?
思路:首先计算+号再计算乘号得到的结果最大,反之结果最小,可以用贪心方法处理,使用栈模拟,处理的时候遇到优先级大的先计算再压入栈中,最后处理优先级小的。
代码如下:
#include<iostream> #include<stack> using namespace std; stack<long long>maxst; stack<long long>minst; int main() { int num; cin>>num; while(num--) { while(!maxst.empty()) maxst.pop(); while(!minst.empty()) minst.pop(); long long val,x,y,z; char ch; cin>>val; maxst.push(val),minst.push(val); while(cin.get(ch)&&ch!=‘\n‘) { cin>>val; if(ch==‘+‘) { x=maxst.top()+val; maxst.pop(); maxst.push(x); minst.push(val); } else if(ch==‘*‘) { x=minst.top()*val; minst.pop(); minst.push(x); maxst.push(val); } } long long maxv=1,minv=0; while(!maxst.empty()) { maxv=maxst.top()*maxv; maxst.pop(); } while(!minst.empty()) { minv=minst.top()+minv; minst.pop(); } cout<<"The maximum and minimum are "<<maxv<<" and "<<minv<<"."<<endl; } return 0; }
[贪心&&栈模拟]uva10700 Camel trading,布布扣,bubuko.com
[贪心&&栈模拟]uva10700 Camel trading
原文:http://blog.csdn.net/zju_ziqin/article/details/21073697