#include #include #include typedef struct WeightBalancedTreeNode{ void *val; int size; struct WeightBalancedTreeNode *left; struct WeightBalancedTreeNode *right; } WBTNode; typedef struct WeightBalancedTreeHead{ WBTNode *root; size_t valSize; int (*cmp)(const void *,const void *); } WBTree; WBTNode* newWBTNode(const void *v,const size_t size){ WBTNode *res=(WBTNode *)malloc(sizeof(WBTNode)); res->val=malloc(size); memcpy(res->val,v,size); res->size=1; res->left=NULL; res->right=NULL; return res; } int getSize(const WBTNode *t){ return t==NULL?0:t->size; } void freeWBTNode(WBTNode *t){ free(t->val); free(t); return; } WBTree* newWBTree(const size_t size,int (*cmp)(const void *,const void *)){ WBTree *res=(WBTree *)malloc(sizeof(WBTree)); res->root=NULL; res->valSize=size; res->cmp=cmp; return res; } void update(WBTNode *t){ if(t==NULL) return; t->size=1+getSize(t->left)+getSize(t->right); return; } WBTNode* leftRotate(WBTNode *v){ WBTNode *u=v->right; v->right=u->left; u->left=v; update(v); update(u); return u; } WBTNode* rightRotate(WBTNode *u){ WBTNode *v=u->left; u->left=v->right; v->right=u; update(u); update(v); return v; } WBTNode* balance(WBTNode *t){ if(t==NULL) return NULL; const double a=(double)1/3; int w=getSize(t)+1; int l=getSize(t->left)+1; int r=getSize(t->right)+1; if(lright->right)+1right=rightRotate(t->right); t=leftRotate(t); } else if(rleft->left)+1left=leftRotate(t->left); t=rightRotate(t); } return t; } WBTNode* insert_func(WBTNode *r,const void *v,WBTree *t){ if(r==NULL) return newWBTNode(v,t->valSize); if(t->cmp(r->val,v)>=0){ r->left=insert_func(r->left,v,t); } else { r->right=insert_func(r->right,v,t); } update(r); return balance(r); } void insert(WBTree *t,const void *v){ t->root=insert_func(t->root,v,t); return; } WBTNode* erase_func_max(WBTNode *r,WBTNode **max){ if(r->right==NULL){ *max=r; return r->left; } r->right=erase_func_max(r->right,max); update(r); return balance(r); } WBTNode* erase_func(WBTNode *r,const void *v,WBTree *t){ if(r==NULL) return NULL; int c=t->cmp(r->val,v); if(c==0){ WBTNode *f=r; if(r->left==NULL){ r=r->right; } else if(r->right==NULL){ r=r->left; } else { WBTNode *max; r->left=erase_func_max(r->left,&max); max->left=r->left; max->right=r->right; r=max; } freeWBTNode(f); } else if(c>0){ r->left=erase_func(r->left,v,t); } else { r->right=erase_func(r->right,v,t); } update(r); return balance(r); } void erase(WBTree *t,const void *v){ t->root=erase_func(t->root,v,t); } void search(WBTree *t,int k,void *res){ if(k<1 || getSize(t->root)root; while(1){ if(getSize(r->left)left); if(k==1){ memcpy(res,r->val,t->valSize); return; } k--; r=r->right; } else { r=r->left; } } } typedef long long int int64; int cmp(const void *a,const void *b){ int64 p=*(int64 *)a; int64 q=*(int64 *)b; return p==q?0:proot)