南桥杯算法训练—表达式计算(有点low)

版权声明:Dream_dog专属 https://blog.csdn.net/Dog_dream/article/details/86710454

问题描述

  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。

输入格式

  输入一行,包含一个表达式。

输出格式

  输出这个表达式的值。

样例输入

1-2+3*(4-5)

样例输出

-4

数据规模和约定

  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。


 题解:比较low的一个算法,栈存取数据一个栈存放运算数据,一个栈存放运算符。遇到括号就递归,每次添加数据前判断数据的长度是否大于0。

代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<bitset>
#include<stack>
#include<vector>
#include<cstring>
#include<string>
#include<map>
#include<cmath>
#include<sstream>
#define clr(a,b) memset(a,b,sizeof(a))
#define pb(a)    push_back(a)
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f3f3f;
const int maxn = 100000 + 2;
const int minn = 100;
string str;
int i;
int pr(char op)
{
	if (op == '+') { return 1; }
	else if (op == '-') { return 1; }
	else if (op == '*') { return 2; }
	else { return 2; }
}
int oper(int a, int b, char op)
{
	if (op == '+') { return a + b; }
	else if (op == '-') { return a - b; }
	else if (op == '*') { return a * b; }
	else { return a / b; }
}
int solve()
{
	stack<int> snum;
	stack<char> op;
	string num;
	for (; i < str.size(); ++i)
	{
		if (str[i] >= '0'&&str[i] <= '9')
		{
			num += str[i];
		}
		else if (str[i] != '('&&str[i] != ')')
		{
			if (num.size() > 0)
				snum.push(atoi(num.c_str()));
			num.clear();
			if (op.size() == 2 && snum.size() == 3)
			{
				int a = snum.top(); snum.pop();
				int b = snum.top(); snum.pop();
				int c = snum.top(); snum.pop();
				char op1 = op.top(); op.pop();
				char op2 = op.top(); op.pop();
				if (pr(op2) >= pr(op1))
				{
					snum.push(oper(c, b, op2));
					snum.push(a); op.push(op1);
				}
				else
				{
					snum.push(c);
					snum.push(oper(b, a, op1));
					op.push(op2);
				}
			}
			op.push(str[i]);
		}
		else if (str[i] == ')')
		{
			if(num.size()>0)
			snum.push(atoi(num.c_str()));
			num.clear();
			break;
		}
		else { num.clear(); ++i; snum.push(solve()); }
	}
	if (op.size() == 2 && snum.size() == 3)
	{
		int a = snum.top(); snum.pop();
		int b = snum.top(); snum.pop();
		int c = snum.top(); snum.pop();
		char op1 = op.top(); op.pop();
		char op2 = op.top(); op.pop();
		if (pr(op2) >= pr(op1))
		{
			snum.push(oper(c, b, op2));
			snum.push(a); op.push(op1);
		}
		else
		{
			snum.push(c);
			snum.push(oper(b, a, op1));
			op.push(op2);
		}
	}
	if (snum.size() > 1)
	{
		int a = snum.top(); snum.pop();
		int b = snum.top(); snum.pop();
		snum.push(oper(b, a, op.top()));
		op.pop();
	}
	return snum.top();
}
int main()
{
	// freopen("input12.txt","r",stdin);

	while (cin >> str)
	{
		i = 0;
		cout << solve() << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Dog_dream/article/details/86710454