Problem 67: 表达式
Time Limit:1 Ms| Memory Limit:128 MB
Difficulty:1
Description
给你一个只有+和*的无括号表达式,给这个表达式加上任意括号,求出这个表达式的最大值和最小值
Input
先是n(n < 10000)表示测试数据组数
接下n行每一行一个表达式,表达式中不会超过100个数,每个数大于等于1小于等于20,测试数据结果不超过longlong类型
接下n行每一行一个表达式,表达式中不会超过100个数,每个数大于等于1小于等于20,测试数据结果不超过longlong类型
Output
按下列事例输出每一行的最大值和最小值
Sample Input
3
1+2*3*4+5
4*18+14+7*10
3+11+4*1*13*12*8+3*3+8
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.
The maximum and minimum are 1560 and 156.
The maximum and minimum are 339768 and 5023.
思路:
此题搭眼一看貌似很麻烦的搜索或者很难的动态规划,再一看,贪心的水题一道。。
求最大值:先算加,后算乘;
求最小值:先算乘,后算加,正常的运算顺序即可!
代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stack>
#define N 500
using namespace std;
stack<long long>sz;
stack<char>fh;
char a[N];
int len;
long long qmax();
long long qmin();
long long jisuan(long long a, long long b, char c);
int main()
{
int n;
scanf("%d", &n);
while(n --){
while(!fh.empty())
fh.pop();
while(!sz.empty())
sz.pop();
scanf("%s", a);
len = strlen(a);
a[len] = '=';
a[len + 1] = '\0';
long long maxn = qmax();
long long minn = qmin();
printf("The maximum and minimum are %lld and %lld.\n", maxn, minn);
}
return 0;
}
long long jisuan(long long a, long long b, char c)
{
switch(c){
case '+':
return a + b;
case '*':
return a * b;
}
return -1;
}
long long qmax() //求最小解时只需复制这块,改两个地方
{
long long x, y, re;
char c, num[5] = {"\0"};
int ni = 0, ls;
for(int i = 0; i <= len; i ++){
if(isdigit(a[i])){
num[ni ++] = a[i];
continue;
}
else{
sscanf(num, "%d", &ls);
sz.push(ls);
memset(num, '\0', sizeof(num));
ni = 0;
}
switch(a[i]){
case '*':
while(!fh.empty()){
x = sz.top();
sz.pop();
y = sz.top();
sz.pop();
c = fh.top();
fh.pop();
re = jisuan(y, x, c);
sz.push(re);
}
fh.push(a[i]);
break;
case '+':
while(!fh.empty() && fh.top() == '+'){
x = sz.top();
sz.pop();
y = sz.top();
sz.pop();
c = fh.top();
fh.pop();
re = jisuan(y, x, c);
sz.push(re);
}
fh.push(a[i]);
break;
case '=':
while(!fh.empty()){
x = sz.top();
sz.pop();
y = sz.top();
sz.pop();
c = fh.top();
fh.pop();
re = jisuan(y, x, c);
sz.push(re);
}
break;
}
}
return sz.top();
}
long long qmin()
{
long long x, y, re;
char c, num[5] = {"\0"};
int ni = 0, ls;
for(int i = 0; i <= len; i ++){
if(isdigit(a[i])){
num[ni ++] = a[i];
continue;
}
else{
sscanf(num, "%d", &ls);
sz.push(ls);
memset(num, '\0', sizeof(num));
ni = 0;
}
switch(a[i]){
case '+':
while(!fh.empty()){
x = sz.top();
sz.pop();
y = sz.top();
sz.pop();
c = fh.top();
fh.pop();
re = jisuan(y, x, c);
sz.push(re);
}
fh.push(a[i]);
break;
case '*':
while(!fh.empty() && fh.top() == '*'){
x = sz.top();
sz.pop();
y = sz.top();
sz.pop();
c = fh.top();
fh.pop();
re = jisuan(y, x, c);
sz.push(re);
}
fh.push(a[i]);
break;
case '=':
while(!fh.empty()){
x = sz.top();
sz.pop();
y = sz.top();
sz.pop();
c = fh.top();
fh.pop();
re = jisuan(y, x, c);
sz.push(re);
}
break;
}
}
return sz.top();
}