堆栈是能支持两个操作的数据结构:
push: a number is inserted at the top of the stack.
push: 将一个数字压入栈顶
If we encounter an operator, we pop the first two numbers from the stack, apply the operator on them, and push the result back onto the stack.
如果我们遇到一个运算符,我们要从堆栈中弹出两个数字,经过运算后,再将结果推入堆栈。
More specifically, the following pseudocode shows how to handle the case when we encounter an operator O:
更具体地讲,下面的伪代码显示了如何处理的情况下,当我们遇到一个操作符O:
Now imagine that we use a queue instead of the stack.
现在想象你用一个队列替换堆栈
A queue also has a push and pop operation, but their meaning is different:
队列也是有push和pop,但是它和堆栈的意义不同。
push: a number is inserted at the end of the queue.pop: the number from the front of the queue is taken out of the queue.
将一个数从队列的开头弹出。
Can you rewrite the given expression such that the result of the algorithm using the queue is the same as the result of the original expression evaluated using the algorithm with the stack?
你可以重写一个的表达式,让使用队列算法的结果和使用该堆栈算法的原始表达式计算的结果一样吗?
Input Specification
Output Specification
gfCecbDdAaEBF
题意:在翻译中写的很详细了。
解析:
如果遇到小写字母直接入栈,如果遇到大写弹出栈顶两个元素。将左指针和右指指向两个元素再入栈。
建立好树后,用二叉树的层次遍历就可以解决问题。
#include <iostream> #include <stdio.h> #include <string.h> #include <stack> using namespace std; struct Node{ Node* left; Node* right; char ch; }; const int N = 10010; Node node[N]; //预先分配N个节点 Node* Q[N]; //建立队列用于二叉树的层次便 void bfs(Node* root) { Q[0] = root; //先将根节点给队列开头 int front = 0; int rear = 1; while(front < rear) { //队列不为空 Node* t = Q[front]->left; if(t != NULL) { Q[rear++] = t; } t = Q[front++]->right; if(t != NULL) { Q[rear++] = t; } } for(int i = rear-1; i >= 0; i--) { putchar(Q[i]->ch); } putchar('\n'); } int main() { int t; string str; int len; while(cin >> t) { while(t--) { cin >> str; stack<Node*> st; len = str.size(); for(int i = 0; i < len ; i++) { node[i].ch = str[i]; if( str[i] >= 'a' && str[i] <= 'z') { //如果是小写字母则入栈 st.push(&node[i]); node[i].left = NULL; node[i].right = NULL; } else { //如果是大写字母则弹出两个操作符赋给左子树和右子树再入栈 node[i].right = st.top(); st.pop(); node[i].left = st.top(); st.pop(); st.push(&node[i]); } } Node* root = &node[len - 1]; bfs(root); //宽搜根节点 } } return 0; }