1 条题解
-
0
#include <bits/stdc++.h> using namespace std; typedef long long ll; map<char, int> mp = {{'+',1},{'-',1},{'*',2},{'/',2}}; stack<char> op; stack<ll> num; bool eval() { if(num.size() < 2) return false; ll a = num.top(); num.pop(); ll b = num.top(); num.pop(); if(op.size() < 1) return false; char c = op.top(); op.pop(); switch(c) { case '+': num.push(b+a); break; case '-': num.push(b-a); break; case '*': num.push(b*a); break; case '/': num.push(b/a); break; } return true; } int main(){ string s; cin>>s; bool flag = false; for(int i=0; i<s.size()-1; i++) { if(isdigit(s[i])) { ll k = 0; while(i < s.size() && isdigit(s[i])) { k = k * 10 + s[i] - '0'; i ++; } i--; if(flag) { k = -k; flag = false; } num.push(k); } else if(s[i] == '(') { op.push(s[i]); } else if(s[i] == ')') { while(op.top() != '(') { if(!eval()) { cout<<"NO"; return 0; } } op.pop(); } else { if(s[i] == '-') { //判断是负数的负号,还是正常的减号 if(i == 0 || s[i-1] == '+' || s[i-1] == '-' || s[i-1] == '*' || s[i-1] == '/' || s[i-1] == '(') { flag = true; continue; } } while(op.size() && mp[op.top()] >= mp[s[i]]) { if(!eval()) { cout<<"NO"; return 0; } } op.push(s[i]); } } while(op.size()) { if(!eval()) { cout<<"NO"; return 0; } } ll ans = num.top(); cout << ans; return 0; }
- 1
信息
- ID
- 836
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 31
- 已通过
- 4
- 上传者