2015年7月1日 星期三

Codeforces Round #306 (Div. 2), problem: (E) Brackets in Implications


分三種:zerocnt = 1 or zerocnt = 2 or zerocnt = 3討論


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cassert>
using namespace std;

typedef long long int int64;

struct node{
    bool val;
    bool is_leaf;
    node *a, *b;
    node(bool v){
        val = v, is_leaf = true;
        return;
    }
    node(node* aa, node* bb){
        a = aa, b = bb; is_leaf = false;
        return;
    }

    void print(){
        if(is_leaf){printf("%d", val);return;}
        printf("(");
        a->print();
        printf(")->(");
        b->print();
        printf(")");
        return;
    }

};

int arr[100011];

vector<node*> build(int a, int b){
    vector<node*> ret;
    for(int lx = a;lx <= b;lx++)
        ret.push_back(new node(arr[lx]));
    return ret;
}

node* from_right(vector<node*> pp){
    assert(pp.size());
    node* prc = pp[(int)(pp.size())-1];
    for(int lx = (int)(pp.size())-2;lx >= 0;lx--)
        prc = new node(pp[lx], prc);
    return prc;
}

int main(){
    int n; scanf("%d", &n);
    for(int lx = 0;lx < n;lx++) scanf("%d", arr+lx);
    
    if(arr[n-1] != 0){
        puts("NO");
        return 0;
    }
    
    int zcnt = 0; for(int lx = 0;lx < n;lx++) zcnt += 1^arr[lx];
    
    if(zcnt == 1){
        puts("YES");
        from_right(build(0, n-1))->print();
        puts("");
    }else if(zcnt == 2){
        if(arr[n-2] == 0){
            puts("NO");
        }else{
            puts("YES");
            int z0, z1 = n-1; for(int lx = 0;lx < n-1;lx++) if(arr[lx] == 0){ z0 = lx; break;}
            (new node(
                new node(
                    from_right(build(0, z0)),
                    from_right(build(z0+1, z1-1))
                ),
                new node(0)
            ))->print();
            puts("");
        }
    }else{
        puts("YES");
        vector<node*> pp;
        int p1 = -1;
        for(int lx = 0;lx < n;lx++){
            if(arr[lx] == 1){
                if(p1 == -1) p1 = lx;
            }else{
                if(p1 == -1) pp.push_back(new node(0));
                else{
                    pp.push_back(from_right(build(p1, lx)));
                    p1 = -1;
                }
            }
        }
        node* tail = pp[(int)pp.size()-1];
        pp.pop_back();
        (new node(
            from_right(pp),
            tail
        ))->print();
        puts("");
    }
    return 0;
}

沒有留言:

張貼留言