Size Balance Tree/不带重复元素 已测 hdu 4217 Data Structure?
如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef long long ll;
#define Max_N 300000
#define size(_) ((_)==NULL ? 0 : (_)->size)
typedef struct sbt{
int val, size;
struct sbt *ch[2];
}SBTNode, *SBT;
SBTNode stack[Max_N];
int sz = 0;
void rotate(SBT *x, int d){
SBT k = (*x)->ch[!d];
(*x)->ch[!d] = k->ch[d];
k->ch[d] = *x;
k->size = (*x)->size;
(*x)->size = size((*x)->ch[0]) + size((*x)->ch[1]) + 1;
(*x) = k;
}
void Maintain(SBT *x, int d){
if ((*x)->ch[d] == NULL) return;
if (size((*x)->ch[d]->ch[d]) > size((*x)->ch[!d])) rotate(x, !d);
else if (size((*x)->ch[d]->ch[!d]) > size((*x)->ch[!d])){
rotate(&((*x)->ch[d]), d), rotate(x, !d);
} else {
return;
}
Maintain(&((*x)->ch[0]), 0);
Maintain(&((*x)->ch[1]), 1);
Maintain(x, 0);
Maintain(x, 1);
}
void insert(SBT *x, int val){
if (*x == NULL){
*x = &stack[sz++];
(*x)->val = val, (*x)->size = 1;
(*x)->ch[0] = (*x)->ch[1] = NULL;
} else {
(*x)->size++;
int d = val > (*x)->val;
insert(&((*x)->ch[d]), val);
Maintain(x, val > (*x)->val);
}
}
void _remove(SBT *x, int val){
if (*x == NULL) return;
(*x)->size--;
if ((*x)->val == val){
if (!(*x)->ch[0] || !(*x)->ch[1]){
*x = (*x)->ch[0] ? (*x)->ch[0] : (*x)->ch[1];
} else {
SBT ret = (*x)->ch[1];
while (ret->ch[0] != NULL) ret = ret->ch[0];
(*x)->val = ret->val;
_remove(&((*x)->ch[1]), ret->val);
}
} else {
int d = val > (*x)->val;
_remove(&((*x)->ch[d]), val);
}
}
int find_kth(SBT x, int k){
int t = 0;
for (;;){
t = size(x->ch[0]);
if (k == t + 1) break;
else if (k < t + 1) x = x->ch[0];
else k -= t + 1, x = x->ch[1];
}
return x->val;
}
int main(){
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
ll ans;
int i, t, n, m, k, tmp, c = 1;
SBT root = NULL;
scanf("%d", &t);
while (t--){
ans = sz = 0, root = NULL;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++) insert(&root, i);
while (m--){
scanf("%d", &k);
ans += tmp = find_kth(root, k);
_remove(&root, tmp);
}
printf("Case %d: %lld\n", c++, ans);
}
return 0;
}