UVA 11234 - Expressions

题目大意:对后缀表达式进行改写,使其以队的方式,在与用栈访问的操作完全一样的前提下(指的是push,pop序列完全一样),计算出

表达式的值,为了确保唯一性表达式不具有交换性。

算法:  本质上是对表达式树的遍历问题,后缀表达式的求值方式是以栈的方式对表达式树进行后序遍历,题目要求的用队遍历,自然想到了对其进行层序遍历,在

一比对发现结果刚好和层序遍历的结果相反,于是便有了答案。


#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <cctype>

using namespace std;
const int size = 10000 + 50;

int  total;
char a[size];
int  b[size] , c[size];

void build(string &str , int start , int finish  , int now)
{
	if(start>=finish)
	{
		b[now] = c[now] = -1;
		return;
	}
	
	int cur = finish - 1;
	int p = 1  , q = 0;
	while(q < p)
	{	
		if(islower(str[cur])) ++q;
		else ++p;
		--cur;
	}
	
	int t = total;
	b[now] = total++;
	c[now] = total++;
	a[t] = str[cur];
	a[t+1] = str[finish-1];
	
	build(str , start, cur , t);
	build(str , cur + 1 , finish - 1 , t + 1);
}

void eval(string &str)
{
	total = 0;
	a[total++] = str[str.size() - 1];
	build(str , 0 , str.size() - 1 , 0);
	
	queue<int> q;
	stack<char> s;
	q.push(0);
	
	while(!q.empty())
	{
		int t = q.front();
		q.pop();
		s.push(a[t]); 
		if(b[t] != -1) q.push(b[t]);
		if(c[t] != -1) q.push(c[t]);
	}
	while(!s.empty())
	{
		cout << s.top();
		s.pop();
	}
	cout << endl;
}

int main()
{
	int n;
	cin >> n; getchar();
	for(int i = 0 ; i < n ; ++i)
	{
		string str;
		getline(cin , str);
		eval(str);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值