求条上官
查看原帖
求条上官
902351
Little_x_starTYJ楼主2023/9/23 14:15
#include <bits/stdc++.h>
using namespace std;
struct node {
	int v, a, o;
};
stack<node> s;
/*
大于栈顶元素则进s,否则出栈
*/
int youxian(char c) {
	if (c == '(')
		return 0;
	if (c == '|')
		return 1;
	return 2;
}
string tail(string a) {
	stack<char> s;
	string b = "";
	for (int i = 0; i < a.size(); i++) {
		if (isdigit(a[i])) {
			b += a[i];
		} else {
			if (a[i] == '(')
				s.push(a[i]);
			else if (a[i] == ')') {
				while (!s.empty() && s.top() != '(') {
					b += s.top();
					s.pop();
				}
				s.pop();
			} else {
				while (!s.empty() && youxian(a[i]) <= youxian(s.top())) {
					b += s.top();
					s.pop();
				}
				s.push(a[i]);
			}
		}
	}
	while (!s.empty()) {
		b += s.top();
		s.pop();
	}
	return b;
}
int main() {
//	freopen("expr.in", "r", stdin);
//	freopen("expr.out", "w", stdout);
	string a;
	cin >> a;
	/*
	转后缀,再运算
	*/
	a = tail(a);
	/*
	算后缀表达式的值
	*/
	for (int i = 0; i < a.size(); i++) {
		if (a[i] == '|') {
			node r = s.top();
			s.pop();
			node l = s.top();
			s.pop();
			s.push({l.v | r.v, l.o + (l.v == 1 ? 1 : r.o), l.a + (l.v == 1 ? 0 : r.a)});
		} else if (a[i] == '&') {
			node r = s.top();
			s.pop();
			node l = s.top();
			s.pop();
			s.push({l.v & r.v, l.o + (l.v == 0 ? 0 : r.o), l.a + (l.v == 0 ? 1 : r.a)});
		} else
			s.push({a[i] - '0', 0, 0});
	}
	node t = s.top();
	s.pop();
	cout << t.v << '\n';
	cout << t.a << ' ' << t.o;
	return 0;
}
2023/9/23 14:15
加载中...