P1175 表达式的转换

题目链接:传送门(点我)

#include<bits/stdc++.h>
using namespace std;

stack<char>s;
int t[5000],cnt;
string in,out="";
int pri[10]={-1,0,1,1,2,2,3};//左括号加减乘除 优先级 
char op[10]={'#','(','+','-','*','/','^'};

int find(char o)
{
	for(int i=2;i<=6;i++)
		if(o==op[i])return 1;
	return 0;
}

int pr(char o)//传入操作符,返回优先级 
{
	for(int i=0;i<7;i++)
		if(op[i]==o)return pri[i];
}

int calc(int x,int y,char o)//x为栈顶数,y为次顶数 y在算式前,x在后 
{
	switch(o){
		case '+':return x+y;
		case '-':return y-x;
		case '*':return x*y;
		case '/':return y/x; 
		case '^':return pow(y,x);
	}
}

int main()
{
	cin>>in;
	s.push('#');
	for(int i=0;i<in.length();i++)
	{
		if(in[i]>='0'&&in[i]<='9')out+=in[i];
		else{//处理符号 
			if(in[i]=='(')s.push(in[i]);
			else{
				if(in[i]==')'){//弹出直到左括号位置
					while(s.top()!='('){
						out+=s.top();s.pop();
					} 
					s.pop();//弹出左括号 
					continue;
				}
				//对符号栈进行操作 
				if(pr(in[i])>pr(s.top()))s.push(in[i]);
				else if(pr(in[i])<=pr(s.top())){
					while(pr(in[i])<=pr(s.top())){out+=s.top();s.pop();}
					s.push((in[i]));
				}	
			}
		}
		
	}
	while(s.top()!='#'){out+=s.top();s.pop();}
	for(int i=0;i<out.length();i++)cout<<out[i]<<" ";
	cout<<endl;
	for(int i=0;i<out.length();i++)
	{
		if(out[i]>='0'&&out[i]<='9')t[cnt++]=out[i]-'0';
		if(find(out[i])){
			int m=t[--cnt];
			int n=t[--cnt];
			int now=calc(m,n,out[i]);
			t[cnt++]=now;
			//cout<<" m:"<<m<<" n:"<<n<<" now:"<<now<<endl;
			for(int j=0;j<cnt;j++)cout<<t[j]<<" ";
			for(int j=i+1;j<out.length();j++)cout<<out[j]<<" ";
			cout<<endl;                
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值