网址如下:
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一样
(对于一个结点,在结点左边的就是左子堆,右边就是右子堆,当然得是优先级更低的结点才包含进去)