#3#9#10RE求助,玄关
查看原帖
#3#9#10RE求助,玄关
785630
YangXiaopei楼主2024/3/5 20:18

附简单注释

#include<bits/stdc++.h>
#define int long long
using namespace std;
int ksm(int a, int b){//幂
	int s = 1;
	while(b){
		if(b & 1){
			s *= a;
		}
		b /= 2;
		a *= a;
	}
	return s;
}
int f(char ch){//级别
	if(ch == '(' || ch == ')'){
		return 0;
	}
	else if(ch == '+' || ch == '-'){
		return 1;
	}
	else if(ch == '*' || ch == '/'){
		return 2;
	}
	return 3;
}
int n, m;
string s, t, str[1000005];
stack<char> st1;
stack<char> st2;
signed main() {
	cin >> s;
	int n = s.size();
	for(int i = 0; i < n; i++){//转中缀
		if(isdigit(s[i])){//数字
			st2.push(s[i]);
		}
		else if(s[i] == '('){//左括号
			st1.push(s[i]);
		}
		else if(s[i] == ')'){//右括号
			char t = st1.top();
			while(t != '('){
				st1.pop();
				st2.push(t);
				t = st1.top();
			}
			st1.pop();
		}
		else if(f(s[i]) >= 1 && f(s[i]) <= 3){//字符
			if(!st1.empty()){
				char t = st1.top();
				while(!st1.empty() && f(s[i]) <= f(t)){
					if(f(s[i]) == f(t) && s[i] == '^'){
						break;
					}
					st1.pop();
					st2.push(t);
					if(!st1.empty()){
						t = st1.top();
					}
				}
			}
			st1.push(s[i]);
		}
	}
	while(!st1.empty()){//把st1剩下的全放进st2
		char t = st1.top();
		st1.pop();
		st2.push(t);
	}
	while(!st2.empty()){//转成倒序
		char t = st2.top();
		st2.pop();
		st1.push(t);
	}
	n = 0;
	while(!st1.empty()){//转成正序存进str[i]
		char t = st1.top();
		n++;
		str[n] = t;
		st1.pop();
		st2.push(t);
	}
	for(int i = 1; i <= n; i++){
		cout << str[i] << " ";
	}
	int cnt = n / 2;
	while(cnt--){
		cout << "\n";
		int tmp = -1;
		for(int i = 1; i <= n; i++){
			if(!isdigit(str[i][0])){//第一个运算符
				tmp = i;
				int a = stoi(str[i - 2]), b = stoi(str[i - 1]);//转数字
				//算答案
				if(str[i][0] == '+'){
					a += b;
				}
				if(str[i][0] == '-'){
					a -= b;
				}
				if(str[i][0] == '*'){
					a *= b;
				}
				if(str[i][0] == '/'){
					a /= b;
				}
				if(str[i][0] == '^'){
					a = ksm(a, b);
				}
				str[i - 2] = to_string(a);//存进去
				break;
			}
		}
		for(int i = tmp + 1; i <= n; i++){//前移2位
			str[i - 2] = str[i];
		}
		n -= 2;
		for(int i = 1; i <= n; i++){//输出
			cout << str[i] << " ";
		}
	}
	return 0;
}
2024/3/5 20:18
加载中...