题目大意:对后缀表达式进行改写,使其以队的方式,在与用栈访问的操作完全一样的前提下(指的是push,pop序列完全一样),计算出
表达式的值,为了确保唯一性表达式不具有交换性。
算法: 本质上是对表达式树的遍历问题,后缀表达式的求值方式是以栈的方式对表达式树进行后序遍历,题目要求的用队遍历,自然想到了对其进行层序遍历,在
一比对发现结果刚好和层序遍历的结果相反,于是便有了答案。
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <cctype>
using namespace std;
const int size = 10000 + 50;
int total;
char a[size];
int b[size] , c[size];
void build(string &str , int start , int finish , int now)
{
if(start>=finish)
{
b[now] = c[now] = -1;
return;
}
int cur = finish - 1;
int p = 1 , q = 0;
while(q < p)
{
if(islower(str[cur])) ++q;
else ++p;
--cur;
}
int t = total;
b[now] = total++;
c[now] = total++;
a[t] = str[cur];
a[t+1] = str[finish-1];
build(str , start, cur , t);
build(str , cur + 1 , finish - 1 , t + 1);
}
void eval(string &str)
{
total = 0;
a[total++] = str[str.size() - 1];
build(str , 0 , str.size() - 1 , 0);
queue<int> q;
stack<char> s;
q.push(0);
while(!q.empty())
{
int t = q.front();
q.pop();
s.push(a[t]);
if(b[t] != -1) q.push(b[t]);
if(c[t] != -1) q.push(c[t]);
}
while(!s.empty())
{
cout << s.top();
s.pop();
}
cout << endl;
}
int main()
{
int n;
cin >> n; getchar();
for(int i = 0 ; i < n ; ++i)
{
string str;
getline(cin , str);
eval(str);
}
return 0;
}