資料結構 + BFS uva 11234 – Expressions

來源:互聯網
上載者:User

 

題目連結:

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;}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.