cogs62 [HNOI2004] 宠物收养所
啦啦啦啦
不维护区间的平衡树题都是树状数组+二分练手题!
不会的参考我的普通平衡树的多种神奇解法之BIT+二分答案
// It is made by XZZ
#include<cstdio>
#include<algorithm>
using namespace std;
#define rep(a,b,c) for(rg int a=b;a<=c;a++)
#define drep(a,b,c) for(rg int a=b;a>=c;a--)
#define erep(a,b) for(rg int a=fir[b];a;a=nxt[a])
#define il inline
#define rg register
#define vd void
typedef long long ll;
il int gi(){
rg int x=0;rg bool flg=0;rg char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')flg=1;ch=getchar();}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return flg?-x:x;
}
const int maxn=80010;
int n;
int t[maxn],tot;
#define lb(o) (o&-o)
il vd Appear(int p){++p;while(p<=tot)++t[p],p+=lb(p);}
il vd Disappear(int p){++p;while(p<=tot)--t[p],p+=lb(p);}
il int Query(int p){int ret=0;while(p)ret+=t[p],p-=lb(p);return ret;}
il int pre(int p){
int mid,l=1,r=p-1,k=Query(p);
while(l<r){
mid=(l+r)>>1;
if(Query(mid+1)==k)r=mid;
else l=mid+1;
}return l;
}
il int nxt(int p){
int mid,l=p+1,r=tot,k=Query(p+1);
while(l<r){
mid=(l+r)>>1;
if(Query(mid+1)^k)r=mid;
else l=mid+1;
}return l;
}
bool z[maxn];
int s[maxn];ll data[maxn];
int main(){
n=gi();
rep(i,1,n)z[i]=gi(),s[i]=data[i]=gi();
sort(data+1,data+n+1);
tot=unique(data+1,data+n+1)-data-1;
rep(i,1,n)s[i]=lower_bound(data+1,data+tot+1,s[i])-data;
++tot;data[0]=-1e16;
int nowtot=0;ll ans=0;
bool nowp;
rep(i,1,n)
if(nowtot==0)Appear(s[i]),nowp=z[i],nowtot=1;
else if(nowp==z[i])Appear(s[i]),++nowtot;
else{
if(Query(s[i])^Query(s[i]+1))Disappear(s[i]);
else{
static int _pre,_nxt;static ll _p,_n;
_pre=_nxt=0;
if(Query(s[i]))_pre=pre(s[i]);
if(Query(s[i]+1)^nowtot)_nxt=nxt(s[i]);
_p=abs(data[s[i]]-data[_pre]),_n=abs(data[s[i]]-data[_nxt]);
ans+=min(_p,_n),ans%=1000000;
Disappear(_n<_p?_nxt:_pre);
}
--nowtot;
}
printf("%lld\n",ans);
return 0;
}