UVA11234 Expressions【BFS】
来源:互联网 发布:天猫和淘宝哪个假货多 编辑:程序博客网 时间:2024/05/22 00:40
题意:给你一个后缀表达式,操作元素为操作符的儿子,输出从叶子到根的按层遍历
思路:
运用后缀表达式进行计算的具体做法:建立一个栈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
- UVA11234 Expressions【BFS】
- UVA11234 - Expressions
- Uva11234 - Expressions
- UVA11234- Expressions
- UVA11234 Expressions
- uva11234
- uva11234-
- uva11234
- 数据结构 + BFS uva 11234 - Expressions
- UVa11234 表达式
- Expressions
- Expressions
- Expressions
- uva 11234 Expressions 表达式 建树+BFS层次遍历
- UVA 11234 - Expressions 二叉树建树+BFS 层次遍历
- uva11234(树)
- 树+栈+队列(表达式树)uva11234
- Regular Expressions
- Android 组合动画(xml)
- 使用vagrant和coreos创建kubernetes集群
- JAVA文件打包成.jar
- PAT (Basic Level) Practise (中文) 1034. 有理数四则运算(20)
- unity插件Behavior designer
- UVA11234 Expressions【BFS】
- zookeeper和kafka集群搭建
- c# 环形队列
- day06作业
- unity之陀螺仪和指南针
- unity_Android显示顶部通知栏
- echarts2.2.7动态数据填充
- python 新建目录,删除目录,判断目录是否存在
- SSM框架构建-详细整合教程(Spring+SpringMVC+MyBatis)