UVA11234 Expressions

题目的意思实在是读不懂,又是把栈变成队列什么的。。不过大体的意思就是把后缀表达式变一下。。

抛开意思,其实就是根据输入建个树,然后倒序输出。。

拿第一个样例说明;大写代表操作符(+ - × /之类的)小写代表数字。。

xyPzwIM:就是指 (xPy) M (zIw) 就像是两数相乘1 × 2写成 12×;

变成树的样子就是

     M

    / |

   P   I

  / |  / |

 x  y z  w


然后把这棵数倒着输出 wzyxIPM;

建树时就是碰到小写,就建个小树,左子树右子数都是空,压入栈;

碰到大写,也要建个小树,并把栈顶两个元素取出来,作为做子树和右子树。。在把新树压入栈

建完后栈顶就是这个树的根,采用广搜遍历就行。。


AC代码:


#include<iostream>
#include<string>
#include<stack>
#include<stdlib.h>
#include<queue>
using namespace std;

const int N = 100010;
struct node{
	char value;
	node *left,*right;
};
int main () {
	int T;
	stack<node*> sta;
	queue<node*> que;
	cin >> T;
	while (T--) {
		string str;
		cin >> str;
		for (int i = 0 ; i < str.size() ;i++) {
			if (str[i] >='a' && str[i] <='z') {
				node* u =(node*)malloc(sizeof(node));
				u -> value = str[i];
				u -> left = u -> right = NULL;
				sta.push(u);
			}
			if (str[i] >= 'A' && str[i] <= 'Z') {
				node* u = (node*)malloc(sizeof(node));
				u -> value = str[i];
				u -> right = sta.top();
				sta.pop();
				u -> left = sta.top();
				sta.pop();
				sta.push(u);
			}
		}
			node* u = sta.top();
			que.push(u);
			int n = 0;
			char res[N];
			while (!que.empty()) {
				u = que.front();
				if(u -> left != NULL)
					que.push(u -> left);
				if(u -> right != NULL)
					que.push(u -> right);
				res[n++] = u -> value;
				que.pop();
			}
			for (int i = n - 1 ;i >= 0 ;i--)
				cout << res[i] ;
			cout << endl;
			while (!sta.empty())
				sta.pop();
	}
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值