样例都过提交10ptso(╥﹏╥)o
查看原帖
样例都过提交10ptso(╥﹏╥)o
681558
Weizhuo_Zhao楼主2024/8/13 23:30
#include <bits/stdc++.h>
using namespace std;
stack<char>s;
map<char, int>p;
stack<int>q;

int count(char f, int a, int b) {
	switch (f) {
		case '+':
			return a + b;
		case '-':
			return a - b;
		case '*':
			return a * b;
		case '/':
			return a / b;
		case '^':
			return pow(a, b);
		default:
			return 0;
	}
}

int main() {
	cin.tie(0);
	cout.tie(0);
	p['('] = 0;
	p['-'] = 1;
	p['+'] = 1;
	p['*'] = 2;
	p['/'] = 2;
	p['^'] = 3;
	p[')'] = 4;
	string str;
	cin >> str;
	int len = 0;
	char a[1000];
	for (int i = 0; i < str.size(); i++) {
//		cout << i << ' ';
		if (str[i] >= '0' && str[i] <= '9') {
			len++;
			a[len] = str[i];
			continue;
		}
		if (str[i] == '(') {
			s.push(str[i]);
			continue;
		}
		if (str[i] == ')') {
//			s.pop();
			while (s.top() != '(' && !s.empty()) {
				len++;
				a[len] = s.top();
//				cout << s.top();
				s.pop();
			}
			s.pop();
			continue;
		}
		if (s.empty())
			s.push(str[i]);
		else if (p[str[i]] <= p[s.top()]) {
			if (str[i] == '^' && p[str[i]] == p[s.top()]) {
//				len++;
//				a[len] = s.top();
				s.push(str[i]);
				continue;
			}
			while (!s.empty() && p[str[i]] <= p[s.top()] && s.top() != '(') {
//				cout << s.top();
				len++;
				a[len] = s.top();
				s.pop();
			}
			s.push(str[i]);
		} else if (p[str[i]] > p[s.top()])
			s.push(str[i]);
	}
	while (!s.empty()) {
//		cout << '|';
		len++;
		a[len] = s.top();
		s.pop();
	}
	for (int i = 1; i <= len; i++)
		cout << a[i] << ' ';
	puts("");
	int l = len, r = 1, sum = 3;
	for (int i = 1; i <= len; i++) {
//		cout << i << ' ';
		if (a[i] >= '0' && a[i] <= '9') {
			q.push(a[i] - '0');
			continue;
		}
		char c = a[i];
		int x = q.top();
		q.pop();
		int y = q.top();
		q.pop();
		q.push(count(c, y, x));
		l = min(l, i - sum);
		sum += 2;
		for (int j = 1; j <= l; j++)
			cout << a[j] << ' ';
		cout << q.top() << ' ';
		r = max(r, i + 1);
		for (int j = r; j <= len; j++)
			cout << a[j] << ' ';
		puts("");
	}
	return 0;
}
2024/8/13 23:30
加载中...