Splay!

时间:2021-07-16 12:51:50
 #include<cstdio>
#include<cstdlib>
const int mod =;
const int inf = ~0u>>;
const int maxn = ;
int lim;
struct SplayTree {
. int sz[maxn];
. int ch[maxn][];
. int pre[maxn];
. int rt,top;
. inline void up(int x){
. sz[x] = cnt[x] + sz[ ch[x][] ] + sz[ ch[x][] ];
. }
. inline void Rotate(int x,int f){
. int y=pre[x];
. ch[y][!f] = ch[x][f];
. pre[ ch[x][f] ] = y;
. pre[x] = pre[y];
. if(pre[x]) ch[ pre[y] ][ ch[pre[y]][] == y ] =x;
. ch[x][f] = y;
. pre[y] = x;
. up(y);
. }
. inline void Splay(int x,int goal){//将x旋转到goal的下面
. while(pre[x] != goal){
. if(pre[pre[x]] == goal) Rotate(x , ch[pre[x]][] == x);
. else {
. int y=pre[x],z=pre[y];
. int f = (ch[z][]==y);
. if(ch[y][f] == x) Rotate(x,!f),Rotate(x,f);
. else Rotate(y,f),Rotate(x,f);
. }
. }
. up(x);
. if(goal==) rt=x;
. }
. inline void RTO(int k,int goal){//将第k位数旋转到goal的下面
. int x=rt;
. while(sz[ ch[x][] ] != k-) {
. if(k < sz[ ch[x][] ]+) x=ch[x][];
. else {
. k-=(sz[ ch[x][] ]+);
. x = ch[x][];
. }
. }
. Splay(x,goal);
. }
. inline void vist(int x){
. if(x){
. printf("结点%2d : 左儿子 %2d 右儿子 %2d %2d sz=%d\n",x,ch[x][],ch[x][],val[x],sz[x]);
. vist(ch[x][]);
. vist(ch[x][]);
. }
. }
. inline void Newnode(int &x,int c){
. x=++top;
. ch[x][] = ch[x][] = pre[x] = ;
. sz[x]=; cnt[x]=;
. val[x] = c;
. }
. inline void init(){
. ans=;type=-;
. ch[][]=ch[][]=pre[]=sz[]=;
. rt=top=; cnt[]=;
. Newnode(rt,-inf);
. Newnode(ch[rt][],inf);
. pre[top]=rt;
. sz[rt]=;
. }
. inline void Insert(int &x,int key,int f){
. if(!x) {
. Newnode(x,key);
. pre[x]=f;
. Splay(x,);
. return ;
. }
. if(key==val[x]){
. cnt[x]++;
. sz[x]++;
. return ;
. }else if(key<val[x]) {
. Insert(ch[x][],key,x);
. } else {
. Insert(ch[x][],key,x);
. }
. up(x);
. }
. void Del(){
. int t=rt;
. if(ch[rt][]) {
. rt=ch[rt][];
. RTO(,);
. ch[rt][]=ch[t][];
. if(ch[rt][]) pre[ch[rt][]]=rt;
. }
. else rt=ch[rt][];
. pre[rt]=;
. up(rt);
. }
. void findpre(int x,int key,int &ans){
. if(!x) return ;
. if(val[x] <= key){
. ans=x;
. findpre(ch[x][],key,ans);
. } else
. findpre(ch[x][],key,ans);
. }
. void findsucc(int x,int key,int &ans){
. if(!x) return ;
. if(val[x]>=key) {
. ans=x;
. findsucc(ch[x][],key,ans);
. } else
. findsucc(ch[x][],key,ans);
. }
. void solve() {
. int a,b,x,y;
. scanf("%d%d",&a,&b);
. if(a==type || sz[rt]==){
.
. Insert(rt,b,),type=a;
. //printf("type=%d\n",type);
. }
. else {
. findpre(rt,b,x);
. findsucc(rt,b,y);
. if(abs(val[x]-b) <= abs(val[y]-b)) {
. ans+=abs(val[x]-b);
. ans%=mod;
. Splay(x,);
. Del();
. }
. else {
. ans+=abs(val[y]-b);
. ans%=mod;
. Splay(y,);
. Del();
. }
. }
. //spt.vist(rt);
. }
. int cnt[maxn];
. int val[maxn];
. int type;
. int ans;
.}spt;
.int main()
.{
. int n;
. scanf("%d",&n);
. spt.init();
. while(n--) spt.solve();
. printf("%d\n",spt.ans);
. return ;
}