计算器
题目描述:
懒的描述了。。就是个中缀表达式变后缀然后计算值
题解:
首先是中缀表达式变后缀:对于有+-*/()的,先搞出符号优先级,分出L和R。然后扫中缀串,遇到数字就放到目标串中,遇到符号就尝试入栈操作根据优先级处理。
其次计算结果,遇到数字入栈,遇到符号计算然后入栈
重点:
复习中缀搞后缀。。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <ctype.h>
#include <limits.h>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <set>
#include <bitset>
#define CLR(a) memset(a, 0, sizeof(a))
#define REP(i, a, b) for(int i = a;i < b;i++)
#define REP_D(i, a, b) for(int i = a;i <= b;i++)
typedef long long ll;
using namespace std;
const int maxn = 300;
int lft[maxn], rgt[maxn];
char mys[maxn];
int stop;
char s[maxn];
char hou_s[maxn];
int hou_n;
int n;
int res;
void getNo()
{
lft[' '] = 0;
lft['+'] = 1;
rgt['+'] = 2;
lft['*'] = 3;
rgt['*'] = 4;
}
void getHou()
{
hou_n = 0;
stop = 0;
mys[0] = ' ';
REP(i, 0, n)
{
if(isdigit(s[i]))
{
hou_s[hou_n] = s[i];
hou_n++;
}
else
{
while(rgt[s[i]] < lft[mys[stop]])
{
hou_s[hou_n] = mys[stop];
hou_n++;
stop--;
}
stop++;
mys[stop] = s[i];
}
}
while(stop!=0)
{
hou_s[hou_n] = mys[stop];
stop--;
hou_n++;
}
}
int cal()
{
stack<int> s;
//int ans = 0;
REP(i, 0, n)
{
if(isdigit(hou_s[i]))
{
s.push(hou_s[i]-'0');
}
else
{
if(hou_s[i]=='+')
{
int a, b, c;
a = s.top();
s.pop();
b = s.top();
s.pop();
c = a + b;
s.push(c);
}
else
{
int a, b, c;
a = s.top();
s.pop();
b = s.top();
s.pop();
c = a * b;
s.push(c);
}
}
}
return s.top();
}
void solve()
{
getHou();
int ansM = cal();
int ansL = s[0]-'0';
REP(i, 1, n)
{
if(s[i] >= '0' && s[i] <= '9')
{
;
}
else
{
if(s[i]=='+')
{
ansL = ansL + s[i + 1]-'0';
i++;
}
else
{
ansL = ansL*(s[i+1]-'0');
i++;
}
}
}
if(ansL==ansM)
{
if(res == ansL)
{
printf("U");
}
else
{
printf("I");
}
}
else
{
if(res==ansL)
{
printf("L");
}
else if(res == ansM)
{
printf("M");
}
else
{
printf("I");
}
}
printf("\n");
}
int main()
{
//freopen("2Bin.txt", "r", stdin);
//freopen("3Bout.txt", "w", stdout);
getNo();
while(scanf("%s", s) != EOF)
{
n = strlen(s);
scanf("%d", &res);
solve();
}
return 0;
}