AC

我是小学生  •  2天前


include <bits/stdc++.h>

using namespace std; stackdat, op; stacksn, sn2; string s;

int level(char c) {

if (c == '^') {
	return 3;
} else if (c == '*' || c == '/') {
	return 2;
} else if (c == '+' || c == '-') {
	return 1;
} else if (c == '(') {
	return 0;
} else {
	return -1;
}

}

void updown_1() {

while (!dat.empty()) {
	op.push(dat.top());
	dat.pop();
}

}

void print_1() {

while (!op.empty()) {
	cout << op.top() << " ";
	dat.push(op.top());
	op.pop();
}

cout << endl;

}

void updown_2() {

while (!sn.empty()) {
	sn2.push(sn.top());
	sn.pop();
}

}

void print_2() {

while (!sn2.empty()) {
	cout << sn2.top() << " ";
	sn.push(sn2.top());
	sn2.pop();
}

}

void trans() {

int len = s.size();

for (int i = 0; i < len; i++) {

	if (s[i] >= '0' && s[i] <= '9') {
		dat.push(s[i]);

	} else if (s[i] == '(') {
		op.push(s[i]);
	} else if (s[i] == ')') {
		while (op.top() != '(') {
			dat.push(op.top());
			op.pop();
		}

		op.pop();
	} else {
		while (!op.empty() && level(op.top()) >= level(s[i])) {
			if (s[i] == '^' && op.top() == '^') {
				break;
			}

			dat.push(op.top());
			op.pop();
		}

		op.push(s[i]);
	}

}

updown_1();

print_1();

}

void cl(char c) {

int x, y;
x = sn.top();
sn.pop();
y = sn.top();
sn.pop();

if (c == '+') {
	sn.push(y + x);
} else if (c == '-') {
	sn.push(y - x);
} else if (c == '*') {
	sn.push(y * x);
} else if (c == '/') {
	sn.push(y / x);
} else if (c == '^') {
	sn.push(pow(y, x));
}

}

void calc() {

updown_1();

while (!op.empty()) {
	char c = op.top();
	op.pop();

	if (c >= '0' && c <= '9') {
		sn.push(c - '0');
	} else {
		cl(c);
		updown_2();
		print_2();
		print_1();
		updown_1();
	}
}

}

int main() {

cin >> s;
s = '(' + s + ')';
trans();
calc();
return 0;

}


评论:

请先登录,才能进行评论