1785:Binary Search Heap Construction

网址如下:

OpenJudge - 1785:Binary Search Heap Construction

唉,最后是WA

也不知道错哪里,也不给我错误的样例

搞得我现在都不知道怎么改(因为不知道错哪)

WA的代码:

#include<cstdio>
#include<string>
#include<cctype>

const int maxn = 50000;

struct Node{
    Node * l, * r;
    std::string lable;
    int priority;
    Node():l(NULL), r(NULL){}
    void input(void);
};

Node node[maxn], * root;
int n, l[maxn], r[maxn];

void Node::input(void){
    getchar(); char c;
    lable.clear();
    while((c = getchar()) != '/') lable.push_back(c);
    scanf("%d", &priority);
    l = r = NULL;
}
void build(void){
    root = node;
    for(int i = 1; i < n; i++){
        int id = i - 1;
        while(id && node[id].priority < node[i].priority) id = l[id];
        l[i] = id;
    }
    r[n - 1] = n - 1;
    for(int i = n - 2; i >= 0; i--){
        int id = i + 1;
        while(id < n - 1 && node[id].priority < node[i].priority) id = r[id];
        r[i] = id;
    }
    //从左到右
    for(int i = 0; i < n; i++){
        root = root->priority > node[i].priority ? root : &node[i];
        int j = r[i];
        if(node[j].priority > node[i].priority){
            if(node[j].l == NULL) node[j].l = &node[i];
        }
    }
    //从右到左
    for(int i = n - 1; i >= 0; i--){
        int j = l[i];
        if(node[j].priority > node[i].priority){
            if(node[j].r == NULL) node[j].r = &node[i];
        }
    }
}
void print(Node * fn){
    if(fn == NULL) return;
    putchar('(');
    print(fn->l);
    printf("%s/%d", fn->lable.c_str(), fn->priority);
    print(fn->r);
    putchar(')');
}

int main(void)
{
    while(scanf("%d", &n) == 1 && n){
        for(int i = 0; i < n; i++) node[i].input();
        build();
        print(root);
        putchar('\n');
    }

    return 0;
}

效率还行吧,时间空间复杂度都是O(n)

其中l和r数组是记录在该位置的左/右边最近的比他大的结点的位置

build的上半部分就是搞这两个数组的

下半部分直接把结点的关系都给连上去,形成一个树

print函数直接打印就完了

顺带一提,这题的描述和shit一样

(对于一个结点,在结点左边的就是左子堆,右边就是右子堆,当然得是优先级更低的结点才包含进去)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值