題目連結:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2175
題目意思:
給一串字元,小寫字母表示運算元,大寫字母表示操作符,求一個字串使該字串用隊列的方式的運行方式的結果與給出串用棧啟動並執行結果一樣。
解題思路:
依據棧的結構構造一棵樹,所求的序列實際上就是這棵樹的按層次逆序輸出。
代碼:
#include<iostream>#include<cmath>#include<cstdio>#include<cstdlib>#include<string>#include<cstring>#include<algorithm>#include<vector>#include<stack>#include<queue>#include<map>#define eps 1e-6#define INF (1<<20)#define PI acos(-1.0)#define Max 11000using namespace std;struct Node{ int father,left,right;};struct Node tree[Max]; //依據棧的結構構造一顆樹char ans[Max];char save[Max];int main(){ int ca; scanf("%d",&ca); while(ca--) { scanf("%s",save); int n=strlen(save); memset(tree,-1,Max*sizeof(struct Node)); stack <int> mystack; for(int i=0;i<n;i++) { if(save[i]>='a'&&save[i]<='z') mystack.push(i); else { int templeft,tempright; tempright=mystack.top(); //注意顯示right,後是left mystack.pop(); templeft=mystack.top(); mystack.pop(); tree[i].left=templeft; tree[i].right=tempright; tree[templeft].father=tree[tempright].father=i; mystack.push(i); } } int root; for(int i=0;i<n;i++) //找到樹根 { if(tree[i].father==-1) { root=i; break; } } queue<int>myqueue; //先BFS遍曆一遍,按順序儲存,然後輸出 int len=0; myqueue.push(root); while(!myqueue.empty()) { int cur=myqueue.front(); myqueue.pop(); ans[len++]=save[cur]; if(tree[cur].left!=-1) //判斷否有左孩子 myqueue.push(tree[cur].left); if(tree[cur].right!=-1) //判斷是否有右孩子 myqueue.push(tree[cur].right); } for(int i=len-1;i>=0;i--) //逆序輸出 putchar(ans[i]); putchar('\n'); } return 0;}