求调字符串计算
  • 板块学术版
  • 楼主zhaozeyao_____
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/9/10 15:06
  • 上次更新2023/11/2 21:38:15
查看原帖
求调字符串计算
1034701
zhaozeyao_____楼主2023/9/10 15:06
#include<bits/stdc++.h>
using namespace std;

stack<char> s;
stack<int> num;
int price[128];

int pow_(int a,int b)
{
	int ans = 1;
	while(b)
	{
		if(b&1)
		{
			ans *= a;
		}
		b >>= 1;
		a *= a;
	}
	return ans;
}

void operation(char t)
{
	int l = num.top();
	num.pop();
	int r = num.top();
	num.pop();
	if(t=='-')
	{
		num.push(r-l);
	}
	else if(t=='+')
	{
		num.push(r+l); 
	}
	else if(t=='*')
	{
		num.push(r*l);
	}
	else if(t=='^')
	{
		num.push(pow_(r,l));
	}
	else 
	{
		if(l==0)
		{
			cout<<"wrong"<<endl;
			exit(0);
		}
		num.push(r/l);
	}
}

void add_char(char t)
{
	if(t==')')
	{
		while(s.top()!='(')
		{
			operation(s.top());
			s.pop();
		}
		s.pop();
	}
	else if(t=='(')
	{
		s.push(t);
	}
	else
	{
		while(price[t]<price[s.top()])
		{
			operation(s.top());
			s.pop();
		}
		s.push(t);
	}
}

void add_int(char t)
{
	num.push(t-'0');
}

void print()
{
	cout<<endl;
	stack<int> n = num;
	stack<char> r = s;
	while(!n.empty())
	{
		cout<<n.top()<<' ';
		n.pop();
	}
	cout<<endl;
	while(!r.empty())
	{
		cout<<r.top()<<' ';
		r.pop();
	}
	cout<<endl;
	cout<<endl;
}

int main()
{
	//ios::sync_with_stdio(false);
	//cin.tie(0);cout.tie(0);
	int n;
	cin>>n;
	s.push('#');
	price['#'] = 0;
	price['+'] = 1;
	price['-'] = 2;
	price['*'] = 3;
	price['/'] = 3;
	price['^'] = 4;
	for(int i = 1;i<=n;i++)
	{
		char t;
		cin>>t;
		if(t=='#')
		{
			return 0;
		}
		else if(t<='9'&&t>='0')
		{
			add_int(t);
			print();
			//cout<<i<<' ';
		}
		else
		{
			add_char(t);
			print();
			//cout<<i<<' ';
		}
	}
	while(s.size()!=1)
	{
		operation(s.top());
		s.pop();
		print();
	}
	cout<<num.top()<<endl;
} 
2023/9/10 15:06
加载中...