求助 1-10全RE 样例全过
查看原帖
求助 1-10全RE 样例全过
569955
niuguanqun楼主2023/11/5 15:35
#include<bits/stdc++.h>
using namespace std;
string s;
int len;
stack<char> dat;
stack<char> op;
stack<int> num;
stack<int> dat2;
int check(char c) {
    if (c == '+') return 1;
    if (c == '-') return 1;
    if (c == '*') return 2;
    if (c == '/') return 2;
    if (c == '^') return 3;
    if (c == '(') return 0;
    if (c == ')') return 0;
    return -1;
}
void popall(char c) {
    if (c == ')') {
        while (op.top() != '(') {
            dat.push(op.top());
            op.pop();
        }
        op.pop();
        return;
    } else if (c == ' ') {
    	while (!op.empty()) {
    		dat.push(op.top());
            op.pop();
		}
	} else {
        while (!((op.empty()) || (check(c) > check(op.top())) || (check(c) == check(op.top()) && c == '^'))) {
            dat.push(op.top());
            op.pop();
        }
        op.push(c);
    }
}
int count(int x, int y, char t) {
    if (t == '+') return x + y;
    if (t == '-') return x - y;
    if (t == '*') return x * y;
    if (t == '/') return x / y;
    if (t == '^') return pow(x, y);
    return -0x7fffffff;
}
int main() {
    getline(cin, s);
    len = s.size();
    for (int i = 0; i < len; i++) {
        if (isdigit(s[i])) dat.push(s[i]);
        else {
            if (s[i] == ')') popall(')');
            else if ((op.empty()) || (s[i] == '(') || (check(s[i]) > check(op.top())) || (check(s[i]) == check(op.top()) && s[i] == '^')) op.push(s[i]);
            else popall(s[i]);
        }
    }
    popall(' ');
    while (!dat.empty()) {
    	op.push(dat.top());
        dat.pop();
	}
	while (!op.empty()) {
    	dat.push(op.top());
    	printf("%c ", op.top());
        op.pop();
	}
	printf("\n");
    while (!dat.empty()) {
    	op.push(dat.top());
        dat.pop();
	}
    while (!op.empty()) {
        char t = op.top();
        op.pop();
        if (isdigit(t)) num.push(t - 48);
        else {
            int x = num.top(), y;
            num.pop();
            y = num.top();
            num.pop();
            num.push(count(y, x, t));
            while (!num.empty()) {
                dat2.push(num.top());
                num.pop();
            }
            while(!dat2.empty()) {
                num.push(dat2.top());
                printf("%d ", dat2.top());
                dat2.pop();
            }
            while(!op.empty()) {
                dat.push(op.top());
                printf("%c ", op.top());
                op.pop();
            }
            while(!dat.empty()) {
                op.push(dat.top());
                dat.pop();
            }
            printf("\n");
        }
    }
	return 0;
}
2023/11/5 15:35
加载中...