原题链接:http://ac.jobdu.com/problem.php?pid=1541
无力吐槽了,c语言中全局变量初始值不是0(指针就是空指针)么?
就这点害我re的快吐啦/(ㄒoㄒ)/~~。。。
题意没啥好说的,套splay tree做。具体如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max_N 1100
#define size(_) ((_)==null ? 0 : (_)->size)
typedef struct _spt{
int val, size;
struct _spt *pre, *ch[2];
}splay;
splay *root = NULL, *null = NULL, stack[Max_N], *ptr[Max_N];
int sz = 0;
splay *_calloc(int val){
splay *p = &stack[sz++];
p->val = val, p->size = 1;
p->pre = p->ch[0] = p->ch[1] = null;
return p;
}
void push_up(splay *x){
if (x == null) return;
x->size = size(x->ch[0]) + size(x->ch[1]) + 1;
}
void rotate(splay *x, int d){
splay *y = x->pre;
y->ch[!d] = x->ch[d];
if (x->ch[d] != null) x->ch[d]->pre = y;
x->pre = y->pre;
if (y->pre != null) y->pre->ch[y->pre->ch[0] != y] = x;
x->ch[d] = y;
y->pre = x;
push_up(y), push_up(x);
if (y == root) root = x;
}
void initialize(){
null = _calloc(-1);
null->size = 0;
root = null;
}
void update(splay *x){
if (x != null){
update(x->ch[0]);
update(x->ch[1]);
push_up(x);
}
}
void gogo(int n){
int i, a, b;
for (i = 0; i <= n; i++){
ptr[i] = _calloc(i);
}
for (i = 1; i <= n; i++){
scanf("%d %d", &a, &b);
if (-1 == a || -1 == b){
if (-1 == a && b != -1) ptr[i]->ch[1] = ptr[b], ptr[b]->pre = ptr[i];
if (-1 == b && a != -1) ptr[i]->ch[0] = ptr[a], ptr[a]->pre = ptr[i];
} else {
ptr[i]->ch[0] = ptr[a], ptr[a]->pre = ptr[i];
ptr[i]->ch[1] = ptr[b], ptr[b]->pre = ptr[i];
}
push_up(ptr[i]);
if (ptr[i]->pre == null) root = ptr[i];
}
update(root);
}
int main(){
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int n, t, i;
char buf[50];
while (~scanf("%d", &n)){
sz = 0, initialize(), gogo(n);
scanf("%d", &t);
while (t--){
scanf("%s %d", buf, &i);
if (‘s‘ == buf[0]){
printf("%d\n", ptr[i]->size);
} else if (‘r‘ == buf[0]){
if (ptr[i] == root) continue;
rotate(ptr[i], ptr[i]->pre->ch[0] == ptr[i]);
} else {
if (ptr[i] == root) printf("-1\n");
else printf("%d\n", ptr[i]->pre->val);
}
}
}
return 0;
}
原文:http://blog.csdn.net/u012077152/article/details/44891135