码迷,mamicode.com
首页 > 其他好文 > 详细

splay树 1285 宠物收养所

时间:2016-01-17 17:32:33      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

#include<cstdio>
#include<iostream>
using namespace std;
int shu[80004][2],n,size,root,kind,zhi[80004],fa[80004],sum=0;
int b1,b2;
void xuan(int a1)
{
	int a2,a3,l,r;
	a2=fa[a1];
	a3=fa[a2];
	if(shu[a2][0]==a1)
	  l=0;
	else
      l=1;
	r=l^1;	
	if(a2==root)
	  root=a1;
	else
	  if(shu[a3][0]==a2)
	    shu[a3][0]=a1;
	  else
	    shu[a3][1]=a1;
	fa[a1]=a3;
	fa[a2]=a1;
	shu[a2][l]=shu[a1][r];
	fa[shu[a1][r]]=a2;
	shu[a1][r]=a2;
	return;
}
void zhuan(int a1)
{
	int y,z;
	for(;a1!=root;)
     {
      y=fa[a1];
	  z=fa[y];	 
	  if(y!=root)
	    if((shu[y][0]==a1)^(shu[z][0]==y))
	  	  xuan(a1);
	    else
	      xuan(y);
	  xuan(a1);
	}
}
void cha(int &a1,int a2,int a3)
{
	if(a1==0)
	  {
	  	size++;
	  	a1=size;
	  	zhi[a1]=a2;
	  	fa[a1]=a3;
	  	zhuan(a1);
	    return;
	  }
	if(a2<zhi[a1])
	  cha(shu[a1][0],a2,a1);
	else
	  cha(shu[a1][1],a2,a1);
	return;
}
void qian(int a1,int a2)
{
	if(a1==0)
	  return;
	if(zhi[a1]<=a2)
	  {
	  	b1=a1;
	  	qian(shu[a1][1],a2);
	  }
	else
	  qian(shu[a1][0],a2);
	return;
}
void hou(int a1,int a2)
{
	if(a1==0)
	  return;
	if(zhi[a1]>=a2)
	  {
	  	b2=a1;
	  	hou(shu[a1][0],a2);
	  }
	else
	  hou(shu[a1][1],a2);
}
void del(int a1)
{
	zhuan(a1);
	if(shu[a1][0]*shu[a1][1]==0)
    	root=shu[a1][0]+shu[a1][1];
	else
	  {
	  	int k=shu[a1][1];
	  	while(shu[k][0])
		  k=shu[k][0];
	  	  shu[k][0]=shu[a1][0];
	  	  fa[shu[a1][0]]=k;
	  	  root=shu[a1][1];
		} 
	fa[root]=0;
	return; 
}
int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	  {
	  	int a1,a2;
	  	scanf("%d%d",&a1,&a2);
	  	if(!root)
	  	  kind=a1;
	  	if(kind==a1)
	  	  cha(root,a2,0);
	  	else
	  	  {
	  	  	b1=-1;
			b2=-1;
	  	  	qian(root,a2);
	  	  	hou(root,a2);
		if(b1==-1)
		  {
		  	sum+=zhi[b2]-a2;
		  	sum%=1000000;
		  	del(b2);
		  }
		 else if(b2==-1)
		  {
		  	sum+=a2-zhi[b1];
		  	sum%=1000000;
			del(b1);
		  }
		  else if(a2-zhi[b1]<=zhi[b2]-a2)
		  {
		  	sum+=a2-zhi[b1];
		  	sum%=1000000;
		  	del(b1);
		  }
		else
		  {
		  	sum+=zhi[b2]-a2;
		  	sum%=1000000;
		  	del(b2);
	      }
		  }
	  }
	printf("%d",sum);
	return 0;
}

splay树 1285 宠物收养所

标签:

原文地址:http://www.cnblogs.com/xydddd/p/5137397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!