求助
查看原帖
求助
527982
NOIAKME楼主2022/8/15 18:33

求助!

P1175 表达式的转换 全RE。。。

求大佬指教!!!

#include<bits/stdc++.h>
using namespace std;
stack<char>st;
stack<int>st1;
char c[10000005];
int cnt=0;
int ans[10000005];
int f=0;
int main(){
	string s;
	cin>>s;
	int n=s.size();
	for(int i=0;i<n;i++){
		if(s[i]>='0'&&s[i]<=9){
			cout<<s[i]<<" ";
			c[++cnt]=s[i];
		}
		else if(s[i]=='('){
			st.push(s[i]);
		}
		else if(s[i]==')'){
			while(st.top()!='('){
				cout<<st.top()<<" ";
				c[++cnt]=st.top();
				st.pop();
			}
			st.pop();
		}
		else if(s[i]=='*'||s[i]=='/'){
			while(!st.empty()&&(st.top()=='*'||st.top()=='/'||st.top()=='^')){
				cout<<st.top()<<" ";
				c[++cnt]=st.top();
				st.pop();
			}
			st.push(s[i]);
		}
		else if(s[i]=='^'){
			st.push(s[i]);
		}
		else{
			while(!st.empty()&&st.top()!='('){
				cout<<st.top()<<" ";
				c[++cnt]=st.top();
				st.pop();
			}
			st.push(s[i]);
		}
	}
	while(!st.empty()){
		cout<<st.top()<<" ";
		c[++cnt]=st.top();
		st.pop();
	}cout<<endl;
	for(int i=1;i<=cnt;i++){
		if(c[i]>='0'&&c[i]<='9'){
		    st1.push((c[i]-'0'));	
		}
		else{
			int a=st1.top();
			st1.pop();
			int b=st1.top();
			st1.pop();
			if(c[i]=='+'){
				st1.push(a+b);
			}
			if(c[i]=='-'){
				st1.push(b-a);
			}
			if(c[i]=='^'){
				st1.push(pow(b,a));
			}
			if(c[i]=='*'){
				st1.push(a*b);
			}
			if(c[i]=='/'){
				st1.push(b/a);
			}
			while(!st1.empty()){
				ans[++f]=st1.top();
				st1.pop();
			}
			for(int j=f;j>=1;j--){
				cout<<ans[j]<<" ";
			}
			for(int j=f;j>=1;j--){
				st1.push(ans[j]);
			}
			f=0;
			for(int j=i+1;j<=cnt;j++){
				cout<<c[j]<<" ";
			}
		}cout<<endl;
	}
	return 0;
} 
2022/8/15 18:33
加载中...