UVa 122 (紫書)

#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<cstdio>
using namespace std;
const int maxn=500;
bool failed=false;
struct Node
{
    bool have_value;
    int v;
    Node *left,*right;
    Node():have_value(false),left(NULL),right(NULL){}
};
Node*root;
Node*newnode(){return new Node();}
void addnode(int v,char*s)
{
    int n=strlen(s);
    Node *u=root;
    for(int i=0;i<n;i++)
    if(s[i]=='L'){if(u->left==NULL)u->left=newnode();
    u=u->left;}
    else if(s[i]=='R'){if(u->right==NULL)u->right=newnode();u=u->right;}
    if(u->have_value)failed=true;
    u->v=v;
    u->have_value=true;
}
bool bfs(vector<int>&ans)
{
    queue<Node*>q;
    ans.clear();
    q.push(root);
    while(!q.empty())
        {
            Node*u=q.front();
            q.pop();
            if(!u->have_value)return false;
            ans.push_back(u->v);
            if(u->left!=NULL)q.push(u->left);
            if(u->right!=NULL)q.push(u->right);
        }
        return true;
}
void remove_tree(Node*u)
{
    if(u==NULL)return;
    remove_tree(u->left);
    remove_tree(u->right);
    delete u;
}
char s[maxn];
bool read_input()
    {
        failed=false;
       remove_tree(root);
       root=newnode();
       for(;;)
       {
           if(scanf("%s",s)!=1)return false;
           if(!strcmp(s,"()"))break;
           int v;
           sscanf(&s[1],"%d",&v);
           addnode(v,strchr(s,',')+1);
       }
       return true;
}
int main()
{
    vector<int>b;
    read_input();
    bfs(b);
    if(failed||!bfs(b)){cout<<"-1";return 0;}
for(vector<int>::iterator it=b.begin();it!=b.end();it++)
cout<<*it<<" ";
}
//測試數據:
//輸入:
//(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
//輸出:5 4 8 11 13 4 7 2 1
//輸入:(3,L) (4,R) ()
//輸出:-1
//萬事開頭難,參考着紫書,看了一下午才把代碼敲出來然後理解了整個程序的過程  題目是 UVa 122  小夥伴們不要直接拷貝我的代碼,因爲我的輸入
//沒有加循環語句,沒法循環輸入,想用的話自己加循環,這樣可以強迫你去看代碼的運行過程,嘿嘿嘿...

發佈了21 篇原創文章 · 獲贊 13 · 訪問量 6858
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章