题目链接
题意:
定义一个运算d:xdy的值是一个区间[x,x*y] (x>=0&&y>=1),即他的值可以去该区间内的任意一个数
然后给你一个中缀表达式,让你输出这个表达式结果的最小值和最大值
解析:
因为d运算的存在,表达式的操作数不再是单个的数字,而是一个二元组[l,r],
(l表示通过该运算所能得到的最小值,r表示通过该运算所能得到的最大值)
那么我们就重新重载+,-,*运算,然后最后套一个计算中缀表达式的板子
比赛时候最后40分钟,网上板子找错了,疯狂RE......
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <iostream>
using namespace std;
#define Min(a,b) (a>=b?b:a)
#define Max(a,b) (a>=b?a:b)
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 5e2+10;
char str[MAXN];
char pp[MAXN];
typedef struct node
{
int l,r;
node(int ll=0,int rr=0):l(ll),r(rr){}
}node;
node operator*(node a,node b)
{
int s,big;
int p1=a.l*b.l;
s=big=p1;
int p2=a.l*b.r;
s=Min(s,p2);
big=Max(big,p2);
int p3=a.r*b.l;
s=Min(s,p3);
big=Max(big,p3);
int p4=a.r*b.r;
s=Min(s,p4);
big=Max(big,p4);
return node(s,big);
}
node operator-(node a,node b)
{
return node(a.l-b.r,a.r-b.l);
}
node operator+(node a,node b)
{
return node(a.l+b.l,a.r+b.r);
}
node operator/(node a,node b)
{
return node(Max(a.l,0),Max(a.r,0)*Max(b.r,1));
}
inline int check(char c)
{
switch (c)
{
case '(':
return 0;
case '+':
case '-':
return 10;
case '*':
return 20;
case '/':
return 21;
case ')':
return 100;
}
}
void trans(char *str)//将中缀表达式转换后缀表达式
{
stack<char>ss;
int i,j;
i=0;
j=0;
while(str[i]!='#')
{
if(str[i]=='(')
{
ss.push(str[i]);
}
else if(str[i]==')')
{
while(ss.top()!='(')
{
pp[j++]=ss.top();
ss.pop();
}
ss.pop();
}
else if(str[i]=='+'||str[i]=='-')
{
while(!ss.empty()&&check(str[i])<=check(ss.top()))
{
pp[j++]=ss.top();
ss.pop();
}
ss.push(str[i]);
}
else if(str[i]=='*'||str[i]=='/')
{
while((!ss.empty()&&check(str[i])<=check(ss.top()))||(!ss.empty()&&check(str[i])<=check(ss.top())))
{
pp[j++]=ss.top();
ss.pop();
}
ss.push(str[i]);
}
else if(str[i]==' ')
{
i++;
continue;
}
else
{
while(str[i]>='0'&&str[i]<='9')
{
pp[j++]=str[i];
i++;
}
i--;
pp[j++]='#';
}
i++;
}
while(!ss.empty())
{
pp[j++]=ss.top();
ss.pop();
}
pp[j]='#';
/*for(int k=0; k<=j; k++)//输出转化后的后缀表达式
{
printf("%c",pp[k]);
}
printf("\n");*/
}
void compvalue()//计算后缀表达式的值
{
int d;
stack<node>mm;
int i;
i=0;
while(pp[i]!='#')
{
if(pp[i]=='+')
{
node r=mm.top();
mm.pop();
node l=mm.top();
mm.pop();
node result=l+r;
mm.push(result);
}
else if(pp[i]=='-')
{
node r=mm.top();
mm.pop();
node l=mm.top();
mm.pop();
node result=l-r;
mm.push(result);
}
else if(pp[i]=='*')
{
node r=mm.top();
mm.pop();
node l=mm.top();
mm.pop();
node result=l*r;
mm.push(result);
}
else if(pp[i]=='/')
{
node r=mm.top();
mm.pop();
node l=mm.top();
mm.pop();
node result=l/r;
mm.push(result);
}
else
{
d=0;
while(pp[i]>='0'&&pp[i]<='9')
{
d=10*d+pp[i]-'0';
i++;
}
mm.push(node(d,d));
}
i++;
}
printf("%d %d\n",mm.top().l,mm.top().r);
}
void solve() //计算中缀表达式的值
{
int n=strlen(str);
str[n]='#';
str[n+1]='\0';
trans(str);
compvalue();
}
int main()
{
while(scanf("%s",str)!=EOF)
{
int i;
for(i=0;str[i];i++) if(str[i]=='d') str[i]='/'; //将d运算定义成'/'
solve();
}
return 0;
}