UVa 122 - Trees on the level

来源:互联网 发布:乐视电视设置网络 编辑:程序博客网 时间:2024/05/21 06:44

好久没出题了,脑子有点钝了。。。



#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<queue>#include<vector>using namespace std;struct Node {    int value;    Node* Ltree;    Node* Rtree;};Node* root;bool failed;Node* new_node() {    return new Node();}void addnode(int v, char* s) {    Node* u = root;    int n = strlen(s);    for(int i = 0; i < n; i++)        if(s[i] == 'L') {            if(u -> Ltree == NULL) u -> Ltree = new_node();            u = u -> Ltree;        } else if(s[i] == 'R') {            if(u -> Rtree == NULL) u -> Rtree = new_node();            u = u -> Rtree;        }    if(u -> value) failed = true;    u -> value = v;}bool read_input() {    failed = false;    char cmd[10];    root = new_node();    for(;;) {        if(scanf("%s", cmd) != 1) return false;        if(!strcmp(cmd, "()")) break;        int v;        sscanf(cmd + 1, "%d", &v);        addnode(v, strchr(cmd, ',') + 1);    }    return true;}bool bfs(vector<int>& ans) {    ans.clear();    queue<Node* > q;    q.push(root);    while(!q.empty()) {        Node* u = q.front(); q.pop();        if(!u -> value) return false;        ans.push_back(u -> value);        if(u -> Ltree != NULL) q.push(u -> Ltree);        if(u -> Rtree != NULL) q.push(u -> Rtree);    }    return true;}void remove_node(Node* tree) {    if(tree == NULL) return ;    remove_node(tree -> Ltree);    remove_node(tree -> Rtree);    delete tree;}int main() {    #ifndef ONLINE_JUDGE        freopen("in.txt", "r", stdin);    #endif // ONLINE_JUDGE    while(read_input()) {        vector<int> ans;        if(bfs(ans)&& !failed)            for(int i = 0; i < ans.size(); i++)                i ? cout << " " << ans[i] : cout << ans[i];        else cout << "not complete";        cout << endl;        remove_node(root);    }    return 0;}


0 0
原创粉丝点击