rt
#include "testlib.h"
#include <string>
#include <stack>
using namespace std;
void getPriority(char ch,int &x) {
if (ch == '(') x=1;
else if (ch == '+' || ch == '-') x= 2;
else if (ch == '*' || ch == '/') x= 3;
else x= 4;
}
void getPostfixExpression(string str,string &x) {
stack<char> mystack;
int size = str.size();
int i = 0;
char tmp;
string res = "";
while (i < size) {
if (str[i] >= '0' && str[i] <= '9') {
res.push_back(str[i]);
}
else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
if (mystack.empty()) {
mystack.push(str[i]);
} else {
while (!mystack.empty()) {
tmp = mystack.top();
int t1,t2;
getPriority(tmp,t1);
getPriority(str[i],t2);
if (t1 >= t2 ){
res.push_back(tmp);
mystack.pop();
} else break;
}
mystack.push(str[i]);
}
} else {
if (str[i] == '(') mystack.push(str[i]);
else {
while (mystack.top() != '(') {
tmp = mystack.top();
res.push_back(tmp);
mystack.pop();
}
mystack.pop();
}
}
i ++;
}
while (!mystack.empty()) {
tmp = mystack.top();
res.push_back(tmp);
mystack.pop();
}
x=res;
}
void calculator(string str,string anss,int &x) {
stack<int> mystack;
vector<int> v1,v2;
int size = str.size();
int len = anss.size();
int num1, num2, num3;
for (int i = 0; i < size; i++) {
if (str[i] >= '0' && str[i] <= '9') {
mystack.push(str[i] - '0');
v1.push_back(str[i]-'0');
} else {
num2 = mystack.top();
mystack.pop();
num1 = mystack.top();
mystack.pop();
if (str[i] == '+') num3 = num1 + num2;
else if (str[i] == '-') num3 = num1 - num2;
else if (str[i] == '*') num3 = num1 * num2;
else if (str[i] == '/') num3 = num1 / num2;
mystack.push(num3);
}
}
for(int i = 0;i < len;i++){
if (anss[i] >= '0' && anss[i] <= '9')
v2.push_back(anss[i]-'0');
}sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
if(v1!=v2)x=114514;
x=mystack.top();
}
void check24(string str,string anss,int &x) {
string res ; getPostfixExpression(str,res);
string ansi; getPostfixExpression(anss,ansi);
int num_res ; calculator(res,ansi,num_res);
x=num_res;
}
int main(int argc, char* argv[]) {
registerTestlibCmd(argc, argv);
while (!ans.eof()) {
string out1 = ouf.readString();
string ans1 = ans.readString();
ans.readEoln();
int tt;check24(out1,ans1,tt);
if (out1 != ans1 && tt!=24){
quitf(_wa, "The answer is wrong: %d",tt);
}
}
quitf(_ok, "The answer is correct.");
return 0;
}
悬赏两关