【题目】
题目描述:
最近,阿 Q 开了一间宠物收养所。收养所提供两种服务:收养被主人遗弃的宠物和让新的主人领养这些宠物。
每个领养者都希望领养到自己满意的宠物,阿 Q 根据领养者的要求通过他自己发明的一个特殊的公式,得出该领养者希望领养的宠物的特点值 ( 是一个正整数,<),而他也给每个处在收养所的宠物一个特点值。这样他就能够很方便的处理整个领养宠物的过程了,宠物收养所总是会有两种情况发生:被遗弃的宠物过多或者是想要收养宠物的人太多,而宠物太少。
1、被遗弃的宠物过多时,假若到来一个领养者,这个领养者希望领养的宠物的特点值为 ,那么它将会领养一只目前未被领养的宠物中特点值最接近 的一只宠物。(任何两只宠物的特点值都不可能是相同的,任何两个领养者的希望领养宠物的特点值也不可能是一样的)如果有两只满足要求的宠物,即存在两只宠物他们的特点值分别为 和 ,那么领养者将会领养特点值为 的那只宠物。
2、收养宠物的人过多,假若到来一只被收养的宠物,那么哪个领养者能够领养它呢?能够领养它的领养者,是那个希望被领养宠物的特点值最接近该宠物特点值的领养者,如果该宠物的特点值为 ,存在两个领养者他们希望领养宠物的特点值分别为 和 ,那么特点值为 的那个领养者将成功领养该宠物。
一个领养者领养了一个特点值为 的宠物,而它本身希望领养的宠物的特点值为 ,那么这个领养者的不满意程度为 。
你得到了一年当中,领养者和被收养宠物到来收养所的情况,希望你计算所有收养了宠物的领养者的不满意程度的总和。这一年初始时,收养所里面既没有宠物,也没有领养者。
输入格式:
第一行为一个正整数 ( ≤ 80000),表示一年当中来到收养所的宠物和领养者的总数。
接下来的 行,按到来时间的先后顺序描述了一年当中来到收养所的宠物和领养者的情况。每行有两个正整数 ,。其中 =0 表示宠物,=1表示领养者, 表示宠物的特点值或是领养者希望领养宠物的特点值。(同一时间呆在收养所中的,要么全是宠物,要么全是领养者,这些宠物和领养者的个数不会超过 10000 个)
输出格式:
输出仅有一个正整数,表示一年当中所有收养了宠物的领养者的不满意程度的总和 mod 1000000 以后的结果。
样例数据:
输入
5 0 2 0 4 1 3 1 2 1 5
输出
3
备注:
【样例说明】
,最后一个领养者没有宠物可以领养。
【分析】
这道题其实不算很难,但是细节卡了我好久。。。
其实我们可以只用一颗平衡树,若宠物过多则树上就记录的是宠物,否则就是领养者,互换着用就行
还是一样的找前驱和后继,分别与当前数作差比较绝对值,删点,再统计答案即可
【代码】
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 80005
#define mod 1000000
#define ll long long
#define lc(x) son[x][0]
#define rc(x) son[x][1]
#define inf (1ll<<50ll)
using namespace std;
int tot,val[N],size[N],weight[N],son[N][2];
void pushup(int root)
{
size[root]=size[lc(root)]+size[rc(root)]+1;
}
void rotate(int &root,int t)
{
int x=son[root][t];
son[root][t]=son[x][t^1];
son[x][t^1]=root;
pushup(root),pushup(x);
root=x;
}
void insert(int &root,int x)
{
if(root)
{
int t=val[root]<x;
insert(son[root][t],x);
if(weight[son[root][t]]<weight[root])
rotate(root,t);
}
else
{
root=++tot;
val[root]=x;
weight[root]=rand();
}
pushup(root);
}
void remove(int &root,int x)
{
if(x==inf||x==-inf) return;
if(val[root]==x)
{
if(!lc(root)&&!rc(root))
{
root=0;
return;
}
rotate(root,weight[lc(root)]<weight[rc(root)]);
remove(root,x);
}
else
remove(son[root][val[root]<x],x);
pushup(root);
}
ll findpre(int root,int x)
{
if(!root) return -inf;
if(val[root]<=x) return max((ll)val[root],findpre(rc(root),x));
return findpre(lc(root),x);
}
ll findsuf(int root,int x)
{
if(!root) return inf;
if(val[root]>=x) return min((ll)val[root],findsuf(lc(root),x));
return findsuf(rc(root),x);
}
int main()
{
int n,i,s,x;
int ans=0,root=0,pet=0,people=0;
srand(time(0));
scanf("%d",&n);
for(i=1;i<=n;++i)
{
scanf("%d%d",&s,&x);
if(pet>0)
{
if(s==0) pet++,insert(root,x);
else
{
ll l=findpre(root,x);
ll r=findsuf(root,x);
ll t=(x-l<=r-x)?l:r;pet--;
remove(root,t),ans=(ans+abs(x-t))%mod;
}
}
else if(people>0)
{
if(s==1) people++,insert(root,x);
else
{
ll l=findpre(root,x);
ll r=findsuf(root,x);
ll t=(x-l<=r-x)?l:r;people--;
remove(root,t),ans=(ans+abs(x-t))%mod;
}
}
else if(pet==0&&people==0)
{
if(s==0) pet++,insert(root,x);
else people++,insert(root,x);
}
}
printf("%d",ans);
return 0;
}