RE 80 玄关求条
查看原帖
RE 80 玄关求条
1033086
HP_Serenity楼主2025/6/27 21:31

如题,蒟蒻代码:

#include <bits/stdc++.h>
#define int long long
using namespace std;
string a, res;
int len;
stack<char> uqe; 
stack<int> uqd;
int change(string x) {
	stringstream ss;
	ss << x;
	int ans;
	ss >> ans;
	return ans;
}
int f(char x) {
	if(x=='^') return 4;
	if(x=='*'||x=='/') return 3;
	if(x=='+'||x=='-') return 2;
	return 1;
}
signed main() {
	cin >> a;
	len = a.size();
	for(int i=0; i<len; i++) {
		if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'||a[i]=='^') {
			while(!uqe.empty()&&f(a[i])<=f(uqe.top())) {
				if(uqe.top()!='(') {
					res.push_back(uqe.top()); 
					res += " ";
				}
				uqe.pop();
			}
			uqe.push(a[i]);
		}
		if(a[i]=='(') uqe.push(a[i]);
		if(a[i]>='0'&&a[i]<='9') {
			int it = i;
			while(a[it]>='0'&&a[it]<='9') it ++;
			string tmp = a.substr(i, it-i);
			res += (tmp+" ");
			i = it-1;
		}
		if(a[i]==')') {
			while(!uqe.empty()&&uqe.top()!='(') {
				res += uqe.top(); res += " ";
				uqe.pop();
			}
			uqe.pop();
		}
	}
	while(!uqe.empty()) {
		res.push_back(uqe.top()); res += " ";
		uqe.pop(); 
	}
	len = res.size();
	for(int i=0; i<len; i++) {
		if(res[i]>='0'&&res[i]<='9') {
			int st = i, ed = i;
			while(res[ed]>='0'&&res[ed]<='9') ed ++;
			string tmp = res.substr(st, ed-st);
			uqd.push(change(tmp));
			i = ed-1;
		} else if(res[i]=='+') {
			int l = uqd.top(); uqd.pop();
			int r = uqd.top(); uqd.pop();
			uqd.push(l+r);
		} else if(res[i]=='-') {
			int l = uqd.top(); uqd.pop();
			int r = uqd.top(); uqd.pop();
			uqd.push(r-l);
		} else if(res[i]=='*') {
			int l = uqd.top(); uqd.pop();
			int r = uqd.top(); uqd.pop();
			uqd.push(l*r);
		} else if(res[i]=='/') {
			int l = uqd.top(); uqd.pop();
			int r = uqd.top(); uqd.pop();
			uqd.push(r/l);
		} else if(res[i]=='^') {
			int l = uqd.top(); uqd.pop();
			int r = uqd.top(); uqd.pop();
			uqd.push(int(pow(r, l)));
		}
	}
	cout << uqd.top();
    return 0;
}

做法猎奇,希望有大佬能看。主要思路是将中缀表达式转成后缀表达式去计算,用字符串存储后缀表达式。change函数起到字符串转数字的功能。

2025/6/27 21:31
加载中...