做法:
如果收养者按照到来顺序收养宠物的话,只要把宠物的特点值建立平衡树,每次求收养者特点值前驱后继与之绝对值相差较小的一个。
这就是一个set的简单应用啦。
如果人和宠物互相选择,可以用两个平衡树,实现起来有些麻烦。
但我们可以想到,人和宠物在此题本质等价,人和宠物都可能待在店里等待。
那其实只要一个平衡树,再加一个变量记录一下当前树中存的是人还是宠物即可,具体见代码。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
using namespace std;
const int INF=1e9;
const int mod=1000000;
set<int>st;
int ans;
void query(int x){
set<int>::iterator l=--st.lower_bound(x),r=st.lower_bound(x);
if(x-*l<=*r-x && *l!=-INF){
ans+=x-*l;
st.erase(l);
}else{
ans+=*r-x;
st.erase(r);
}
ans%=mod;
}
int main(){
int n;
int op;
scanf("%d",&n);
while(n--){
int a,b;
scanf("%d%d",&a,&b);
st.insert(-INF);
st.insert(INF);
if(st.size()==2){
op=a;
st.insert(b);
}else if(a==op) st.insert(b);
else query(b);
}
printf("%d",ans);
return 0;
}
^_^