csu - 1537: Miscalculation (模拟题)

解析ACM CSU在线编程题解
本文详细解析了ACM CSU在线Judge平台的一个编程题目,通过使用两个栈来处理符号和数字,实现对表达式的计算和验证。重点在于理解和应用栈的数据结构解决数学表达式求值的问题。

http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1537

因为给出的式子是必定合法的,只要用两个栈分别保存符号和数字.算出答案后和从左至右算的答案比对即可.

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <vector>
 5 #include <cstring>
 6 #include <algorithm>
 7 #include <string>
 8 #include <set>
 9 #include <functional>
10 #include <numeric>
11 #include <sstream>
12 #include <stack>
13 #include <map>
14 #include <queue>
15 
16 #define CL(arr, val)    memset(arr, val, sizeof(arr))
17 
18 #define ll long long
19 #define inf 0x7f7f7f7f
20 #define lc l,m,rt<<1
21 #define rc m + 1,r,rt<<1|1
22 #define pi acos(-1.0)
23 
24 #define L(x)    (x) << 1
25 #define R(x)    (x) << 1 | 1
26 #define MID(l, r)   (l + r) >> 1
27 #define Min(x, y)   (x) < (y) ? (x) : (y)
28 #define Max(x, y)   (x) < (y) ? (y) : (x)
29 #define E(x)        (1 << (x))
30 #define iabs(x)     (x) < 0 ? -(x) : (x)
31 #define OUT(x)  printf("%I64d\n", x)
32 #define lowbit(x)   (x)&(-x)
33 #define Read()  freopen("din.txt", "r", stdin)
34 #define Write() freopen("dout.txt", "w", stdout);
35 
36 
37 using namespace std;
38 
39 int main()
40 {
41     //freopen("a.txt","r",stdin);
42     char s[25];
43     int num;
44     scanf("%s",s);
45     scanf("%d",&num);
46     stack<int>s1;
47     stack<char>s2;
48     int l=strlen(s);
49     for(int i=0;i<l;i++)
50     {
51         if(s[i]>='0'&&s[i]<='9') s1.push(s[i]-'0');
52         else if(s[i]=='*')
53         {
54             int x=s1.top();s1.pop();
55             int y=s[i+1]-'0';
56             s1.push(x*y);
57             i++;
58         }
59         else s2.push('+');
60     }
61     while(!s2.empty())
62     {
63         int x=s1.top();s1.pop();
64         int y=s1.top();s1.pop();
65         s1.push(x+y);
66         s2.pop();
67     }
68     int sum=s[0]-'0';
69     for(int i=1;i<l;i++)
70     {
71         if(s[i]=='+') sum=sum+(s[i+1]-'0');
72         else if(s[i]=='*') sum=sum*(s[i+1]-'0');
73     }
74     //printf("%d %d\n",s1.top(),sum);
75     if(s1.top()==sum&&sum==num) printf("U\n");
76     else if(s1.top()!=num&&sum!=num) printf("I\n");
77     else if(s1.top()==num&&sum!=num) printf("M\n");
78     else if(s1.top()!=num&&sum==num) printf("L\n");
79     return 0;
80 }

 

转载于:https://www.cnblogs.com/nowandforever/p/4605610.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值