UVA11234 Expressions【BFS】
2017-09-04 18:22
501 查看
题意:给你一个后缀表达式,操作元素为操作符的儿子,输出从叶子到根的按层遍历
思路:
运用后缀表达式进行计算的具体做法:建立一个栈S 。从左到右读表达式,如果读到操作数就将它压入栈S中,如果读到n元运算符(即需要参数个数为n的运算符)则取出由栈顶向下的n项按操作数运算,再将运算的结果代替原栈顶的n项,压入栈S中 。如果后缀表达式未读完,则重复上面过程,最后输出栈顶的数值则为结束。
小写字母为操作元素,大写为操作符,遇到操作符,取出操作元素是建树。最后从根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; }
相关文章推荐
- 数据结构 + BFS uva 11234 - Expressions
- uva 11234 Expressions 表达式 建树+BFS层次遍历
- uva 11234 Expressions 表达式 建树+BFS层次遍历
- UVa 11234 Expressions (二叉树重建&由叶往根的层次遍历)
- UVA 11234 Expressions(数据结构,二叉树,栈,队列)
- UVA 11234 - Expressions
- UVa 11234 Expressions
- UVa 11234 - Expressions
- UVa 11234 - Expressions
- uva 11234 Expressions(建立二叉树+层次遍历)
- Uva 11234 Expressions (二叉树的层次遍历)
- uva 11234 Expressions
- UVa 11234 - Expressions
- UVa 11234 Expressions
- UVA 11234 Expressions
- UVa 11234 - Expressions
- uva11234 - Expressions
- UVA 11234 Expressions
- UVa 11234 - Expressions
- UVA 11234 - Expressions