UVA11234 Expressions【BFS】

题意:给你一个后缀表达式,操作元素为操作符的儿子,输出从叶子到根的按层遍历


思路:

运用后缀表达式进行计算的具体做法:建立一个栈S 。从左到右读表达式,如果读到操作数就将它压入栈S中,如果读到n元运算符(即需要参数个数为n的运算符)则取出由栈顶向下的n项按操作数运算,再将运算的结果代替原栈顶的n项,压入栈S中 。如果后缀表达式未读完,则重复上面过程,最后输出栈顶的数值则为结束。
小写字母为操作元素,大写为操作符,遇到操作符,取出操作元素是建树。最后从根BFS(按层遍历),逆着输出即可

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e4+5;
struct data
{
	int l,r;
}node[maxn];
int ans[maxn],tot;
char s[maxn];
stack<int> st;

void init(int x)
{
	while(!st.empty())
		st.pop();
	for(int i = 0; i <= x; i++)
		node[i].l = node[i].r = -1;
}

void bfs()
{
	queue<int> q;
	while(!q.empty()) q.pop();
	q.push(strlen(s)-1);
	tot = 0;
	while(!q.empty())
	{
		int x = q.front();q.pop();
		ans[tot++] = x;
		if(node[x].l != -1)
			q.push(node[x].l);
		if(node[x].r != -1)
			q.push(node[x].r);	
	}
	for(int i = tot-1; i >= 0; i--)
		putchar(s[ans[i]]);
	putchar('\n');
}

int main(void)
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%s",&s);
		init(strlen(s));
		for(int i = 0; s[i] != '\0'; i++)
		{
			if(s[i] >= 'a' && s[i] <= 'z')
				st.push(i);
			else
			{
				node[i].r = st.top();st.pop();
				node[i].l = st.top();st.pop();
				st.push(i);
			}
		}
		bfs();
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值