#include <stdio.h>
#include <stdlib.h>
#define height 4
#define MAX (1<<height) //ビットシフト演算 2^height と同じ
int t[MAX+1]; //配列外アクセス防止のためのダミーで+1
int sz = 0;
void swap(int *x, int *y){
int tmp = *x;
*x = *y;
*y = tmp;
}
void initTree(int n){
int i;
for(i=0;i<MAX;i++){
t[i] = -1;
}
}
void printA(){
int i;
for(i
=1;i
<=sz
;i
++) printf("%d ",t
[i
]); }
void printT(int i){
int x = i;
while(x/2!=0){
x/=2;
}
}
int goP(int i){
if(i/2 == 0) return 0;
else return i/2;
}
int goL(int i){
if(2*i >= MAX) return 0;
else return 2*i;
}
int goR(int i){
if(2*i+1 >= MAX) return 0;
else return 2*i+1;
}
void preOrder(int i){
if(t[i] == -1) return;
printT(i);
preOrder(goL(i));
preOrder(goR(i));
}
void inOrder(int i){
if(t[i] == -1) return;
inOrder(goL(i));
printT(i);
inOrder(goR(i));
}
void postOrder(int i){
if(t[i] == -1) return;
postOrder(goL(i));
postOrder(goR(i));
printT(i);
}
void insBT(int x){
int k,i = 1;
for(k=0;k<height;k++){
if(t[i]==-1){
t[i] = x;
sz++;
return;
}
if(x < t[i]) i = goL(i);
else i = goR(i);
}
printf("Error : too high -> %d\n",x
); }
int popHeap(){
int i=1;
int l,r,ma;
int ret=t[i];
t[i]=t[sz];
t[sz--]=-1;
while(i*2<=sz){
l=goL(i);
r=goR(i);
if(t[l]<t[r]) ma=r;
else ma=l;
if(t[i]>t[ma]) break;
swap(&t[i],&t[ma]);
i=ma;
}
return ret;
}
void pushHeap(int x){
int i=++sz;
int p;
if(i>=MAX-1){
printf("Error : out size <%d - > %d\n",MAX
-1,i
); t[sz]=-1;
sz--;
return ;
}
t[sz]=x;
while(1<i){
p=goP(i);
if(t[i]<=t[p]) return ;
else swap(&t[i],&t[p]);
i=p;
}
}
int main(void){
int i,x,n;
// 木の初期化
initTree(n);
for(i=0;i<n;i++){
}
sz = n;
// 中間順で表示
inOrder(1);
// pop
int a=popHeap();
inOrder(1);
a = popHeap();
inOrder(1);
pushHeap(100);
inOrder(1);
pushHeap(30);
inOrder(1);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KIAojZGVmaW5lIGhlaWdodCA0CiNkZWZpbmUgTUFYICgxPDxoZWlnaHQpICAvL+ODk+ODg+ODiOOCt+ODleODiOa8lOeulyAyXmhlaWdodCDjgajlkIzjgZgKIAppbnQgdFtNQVgrMV07IC8v6YWN5YiX5aSW44Ki44Kv44K744K56Ziy5q2i44Gu44Gf44KB44Gu44OA44Of44O844Gn77yL77yRCmludCBzeiA9IDA7CiAKdm9pZCBzd2FwKGludCAqeCwgaW50ICp5KXsKICAgIGludCB0bXAgPSAqeDsKICAgICp4ID0gKnk7CiAgICAqeSA9IHRtcDsKfQogCnZvaWQgaW5pdFRyZWUoaW50IG4pewogICAgaW50IGk7CiAgICBmb3IoaT0wO2k8TUFYO2krKyl7CiAgICAgICAgdFtpXSA9IC0xOwogICAgfQp9CiAKdm9pZCBwcmludEEoKXsKICAgIGludCBpOwogICAgZm9yKGk9MTtpPD1zejtpKyspIHByaW50ZigiJWQgIix0W2ldKTsKICAgIHByaW50ZigiXG4iKTsKfQogCnZvaWQgcHJpbnRUKGludCBpKXsKICAgIGludCB4ID0gaTsKICAgIHdoaWxlKHgvMiE9MCl7CiAgICAgICAgcHJpbnRmKCIgICIpOwogICAgICAgIHgvPTI7CiAgICB9CiAgICBwcmludGYoIiVkXG4iLHRbaV0pOwp9CiAKaW50IGdvUChpbnQgaSl7CiAgICBpZihpLzIgPT0gMCkgcmV0dXJuIDA7CiAgICBlbHNlIHJldHVybiBpLzI7Cn0KIAppbnQgZ29MKGludCBpKXsKICAgIGlmKDIqaSA+PSBNQVgpIHJldHVybiAwOwogICAgZWxzZSByZXR1cm4gMippOwp9CiAKaW50IGdvUihpbnQgaSl7CiAgICBpZigyKmkrMSA+PSBNQVgpIHJldHVybiAwOwogICAgZWxzZSByZXR1cm4gMippKzE7Cn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