BZOJ 1208 HNOI 2004 宠物收养所 splay

题目大意啥的自便吧,本问是题目的splay做法,之前发过用set写的 ,有兴趣可以转         

http://www.cnblogs.com/evan-oi/archive/2012/03/24/2415297.html

 

简单slpay题,其实一个NB的操作都没有...话说人挑狗个狗挑人都是一样的,splay tree里有人存人,没人存狗...查找就一边递归一遍打擂台然后更新就好了。

代码:

View Code
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
#define MaxN 10010
#define mod 1000000
#define INF 200000000
struct atp
{
int lc,rc,f,data;
}a[MaxN*10];

int n,kind,sum=0,root=0,tot=0,ans=0,temp;

void Right(int x)
{
int y=a[x].f;
int z=a[y].f,c=a[x].rc;
if (a[z].lc==y) a[z].lc=x; else a[z].rc=x; a[x].f=z;
a[y].f=x;a[x].rc=y;
a[y].lc=c;a[c].f=y;
}
void Left(int x)
{
int y=a[x].f;
int z=a[y].f,c=a[x].lc;
if(a[z].lc==y) a[z].lc=x; else a[z].rc=x;a[x].f=z;
a[y].f=x;a[x].lc=y;
a[y].rc=c;a[c].f=y;
}
void splay(int &root,int x)
{
int y,z;
while (x!=root)
{
y=a[x].f;z=a[y].f;
if(y==root)
{
if (a[y].lc==x) Right(x); else Left(x);
root=x;
} else
if (a[z].lc==y)
if (a[y].lc==x) Right(y),Right(x); else
Left(x),Right(x); else
if (a[y].rc==x) Left(y),Left(x); else
Right(x),Left(x);
if(z==root) root=x;
}
}
void insert(int &t,int x,int f)
{
if (t==0)
{
tot++;
t=tot;
a[t].lc=a[tot].rc=0;
a[t].data=x;
a[t].f=f;
splay(root,t);
} else
if (a[t].data<x) insert(a[t].rc,x,t); else
if (a[t].data>x) insert(a[t].lc,x,t);
}

void find(int t,int y)
{
if (t==0) return ;
if (abs(a[temp].data-y)>abs(a[t].data-y) ||
(abs(a[temp].data-y)==abs(a[t].data-y) && a[temp].data>a[t].data) ) temp=t;
if (y>a[t].data && a[t].rc) find(a[t].rc,y); else
if (y<a[t].data && a[t].lc) find(a[t].lc,y);
}

int getmax(int x)
{
if (!a[x].rc) return x; else
return getmax(a[x].rc);
}

void Delete(int &x)
{
if (a[x].lc==0 && a[x].rc==0) x=0; else
if (a[x].rc==0 && a[x].lc) a[a[x].lc].f=0,x=a[x].lc; else
if (a[x].lc==0 && a[x].rc) a[a[x].rc].f=0,x=a[x].rc; else
{
int t=getmax(a[x].lc);
splay(a[x].lc,t);
a[t].rc=a[x].rc;
a[a[x].rc].f=t;
a[t].f=0;
a[x].lc=a[x].rc=a[x].data=a[x].f=0;
x=t;
}
}
int main()
{
freopen("in","r",stdin);
int x,y;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{

scanf("%d%d",&x,&y);
if (sum==0 || kind==x)
{
insert(root,y,0);
sum++;
kind=x;
} else
{
sum--;
temp=root;
find(root,y);
ans+=abs(a[temp].data-y);
ans%=mod;
splay(root,temp);
Delete(root);
}
}
printf("%d\n",ans);
return 0;
}



posted @ 2012-03-31 16:31  Evan1004  阅读(199)  评论(0编辑  收藏  举报