bzoj1208:[HNOI2004]宠物收养所-splay

4 篇文章 0 订阅
1 篇文章 0 订阅

这个splay维护的不是下标,维护的是数值,所以每必要记下size 还有各种标记

只要能够插入一个数,删除一个数,找一个不在树中的数的前驱和后继就可以了。

需要想的是这道题并不需要用两个splay或者记下多余的没用掉的宠物或者人,只要用一个splay就好了,因为题目中说了任意时刻宠物店中只有人或者只有宠物,这样轮换着用一个splay就好了orz...

好奇怪,这道题在家里写了一天都是WA,在学校机房1A了orz....

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define MAXN 80010
#define P 1000000
int n,kind,a,b,root,tot,x1,x2;
long long ans;
struct node{
	int ch[2],v,f;
}tr[MAXN];
inline bool d(int x) {return tr[tr[x].f].ch[1]==x;}
void SC(int x,int y,int z)
{
	tr[x].ch[z]=y;tr[y].f=x;
}
void rot(int x)
{
	int y=tr[x].f,z=tr[y].f,t=d(x);
	SC(z,x,d(y));SC(y,tr[x].ch[!t],t);SC(x,y,!t);
}
void splay(int x,int f)
{
	if (!x) return  ;
	if (f==0) root=x;
	while (tr[x].f!=f)
	{
		if (tr[tr[x].f].f==f) {rot(x);break;}
		if (d(x)==d(tr[x].f)) {rot(tr[x].f);rot(x);} else {rot(x);rot(x);}
	}
}
void Insert(int y)
{
	if (root==0) 
	{
		root=++tot;
		tr[tot].v=y;tr[tot].f=0;
		tr[0].ch[1]=root;
		return ;
	}
	int x=root,p=0;
	while (x)
	{
		p=x;
		if (tr[x].v<y) x=tr[x].ch[1];  else x=tr[x].ch[0];
	}
	if (tr[p].v<y) 
	{
		tr[p].ch[1]=++tot;tr[tot].v=y;tr[tot].f=p;
	}
	else 
	{
		tr[p].ch[0]=++tot;tr[tot].v=y;tr[tot].f=p;
	}
	splay(tot,0);
}
void pre(int x,int y)
{
	if (!x) return ;
	if (tr[x].v<=y) {x1=x;pre(tr[x].ch[1],y);}
	else pre(tr[x].ch[0],y);
}
void suc(int x,int y)
{
	if (!x) return ;
	if (tr[x].v>=y) {x2=x;suc(tr[x].ch[0],y);}
	else suc(tr[x].ch[1],y); 
}
void del(int x)
{
	splay(x,0);
	if (tr[x].ch[0]==0)
	{
		root=tr[x].ch[1];
		tr[root].f=0;
	}
	else
	{
		int y=tr[x].ch[0];
		while (tr[y].ch[1]) y=tr[y].ch[1];
		splay(y,x);
		root=y;
		tr[y].f=0;
		tr[y].ch[1]=tr[x].ch[1];
		tr[tr[x].ch[1]].f=y;
	}
}
void dfs(int x)
{
	if (!x) return ;
	dfs(tr[x].ch[0]);
	printf("%d ", tr[x].v);
	dfs(tr[x].ch[1]);
}
int main()
{
	scanf("%d", &n);
	kind=0;
	for (int i=1;i<=n;i++)
	{
		scanf("%d%d", &a, &b);
		if (kind==a)  Insert(b);
		else if (root==0) {kind=a;Insert(b);}
		else
		{
			x1=x2=-1;
			pre(root,b);suc(root,b);
			if (x1==-1) {ans=(ans+tr[x2].v-b) % P;del(x2);}
			else if (x2==-1) {ans=(ans+b-tr[x1].v) % P;del(x1);}
			else
			{
				if (b-tr[x1].v<=tr[x2].v-b) {ans=(ans+b-tr[x1].v) % P;del(x1);}
				else {ans=(ans+tr[x2].v-b) % P;del(x2);}
			}
		}
		//dfs(root);printf("\n");
	}
	printf("%lld\n", ans);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值