sicily 1149

搞了三个小时。。我终于发现是我在处理括号的时候出问题。。。交了。。AC了。。。内牛满面sicily 1149_第1张图片

 

#include <iostream> #include <stack> #include <string> #include <cmath> #include <map> #include <vector> #include <cstdlib> using namespace std; stack<long long> _operand; stack<char> _operator; map<char, string> sv; int isp(char c) { switch(c) { case '+': case '-': return 2; case '*': //case '/': return 4; case '^': return 6; case '(': return 0; } } int osp(char c) { switch(c) { case '+': case '-': return 1; case '*': //case '/': return 3; case '^': return 5; case '(': return 8; case ')': return -1; } } void cal() { char c = _operator.top(); _operator.pop(); long long x = _operand.top(); _operand.pop(); long long y = _operand.top(); _operand.pop(); switch(c) { case '+': _operand.push(y + x); break; case '-': _operand.push(y - x); break; case '*': _operand.push(y * x); break; //case '/': // _operand.push(y / x); // break; case '^': long long s = 1; //注意0次方的情况 for(int i = 1; i <= x; i++) s *= y; _operand.push(s); break; } } long long calc(string &s, int j) { string num; while(!_operator.empty()) { _operator.pop(); } while(!_operand.empty()) { _operand.pop(); } for(int i = 0; i < s.size(); i++) { if(s[i] == 'a') { _operand.push(j); continue; } if(s[i] == ' ') continue; if(s[i] >= '0'&& s[i] <= '9') { num += s[i]; }else { if(!num.empty()) { _operand.push(atoi(num.c_str())); num.clear(); } while(!_operator.empty() && isp(_operator.top()) > osp(s[i])) { if(_operator.top() == '(') { _operator.pop(); break; } cal(); } if(s[i] != ')') _operator.push(s[i]); } } if(!num.empty()) { _operand.push(atoi(num.c_str())); num.clear(); } while(!_operator.empty()) { cal(); } return _operand.top(); } int main() { string s; getline(cin, s); int n; cin >> n; string stmp; getline(cin, stmp); for(int i = 0; i < n; i++) { getline(cin, stmp); sv.insert(make_pair(i + 'A', stmp)); } for(int j = 1; j < 10000 ; j++) { if(sv.size() <= 1) break; //保证有解 long long ans = calc(s, j); //cout << ans << " "; //system("pause"); vector<map<char, string>::iterator > iter; for(map<char, string>::iterator i = sv.begin(); i != sv.end(); i++) { long long ans1 = calc(i->second, j); //cout << ans1 << " "; if(ans1 != ans) iter.push_back(i); } for(vector<map<char, string>::iterator >::iterator i = iter.begin(); i != iter.end(); i++) sv.erase(*i); //cout << endl; } for(map<char, string>::iterator i = sv.begin(); i != sv.end(); i++) cout << i->first; cout << endl; return 0; } 

你可能感兴趣的:(c,String,iterator,iostream,pair)