您的位置:首页 > 其它

UVa 11234 - Expressions

2016-03-10 17:41 411 查看
題目:已知一個計算表達式的棧的表述形式,輸出對應的隊列的表達形式。

分析:數據結構。




如上圖所示,是數據而的表達式樹。

對應的棧表達形式,用類似樹的後根序輸出可以表示為:輸出右子樹;輸出左子樹;輸出根;(dfs)

對應的隊列表達形式,為從下到上,從左到有的表示;(bfs)

因此,利用棧處理生成對應的表達式樹,然後在利用bfs分層掃描即可;

bfs計算順序為從上倒下,從有到左計算(先右子樹,再左子樹),逆序存儲輸出即可。

說明:網絡質量好差╮(╯▽╰)╭。

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <cstdio>

using namespace std;

char input[10001];
char output[10001];

typedef struct _tnode 
{
	char   value;
	_tnode *Lchild;
	_tnode *Rchild;
}tnode;
tnode Node[10001];
tnode*Stack[10001];
tnode*Queue[10001];

int main()
{
	int t;
	while (~scanf("%d",&t)) {
		while (t --) {
			scanf("%s",input);
			
			//dfs 构建运算树 
			int top = 0, count = 0;
			for (int i = 0; input[i]; ++ i) {
				Node[count].value = input[i];
				if (input[i] >= 'a' && input[i] <= 'z') {
					Node[count].Lchild = 0;
					Node[count].Rchild = 0;
					Stack[top ++] = &Node[count ++];
				}else {
					Node[count].Lchild = Stack[top-1];
					Node[count].Rchild = Stack[top-2];
					Stack[top-2] = &Node[count ++];
					top = top-1;
				}
			}
			
			//bfs 转化运算顺序 
			int head = 0, tail = 0, save = count;
			output[save] = 0;
			Queue[tail ++] = Stack[0];
			while (head < tail) {
				tnode* now = Queue[head ++];
				output[-- save] = now->value;
				if (now->Rchild) {
					Queue[tail ++] = now->Rchild;
				}
				if (now->Lchild) {
					Queue[tail ++] = now->Lchild;
				}
			}
			
			puts(output);
		}
	}
	
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: