// 大视野 1208 Splay 初步
//
// 解题思路:
// 要么都是宠物,要么都是人,而且是一个一个来的,那么只要简单的插入就好了
// 一个一个的插入和查找,就能ac.
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdio>
#define For(x,a,b,c) for (int x = a; x <= b; x += c)
using namespace std;
const int MAX_N = 1e5 + 8;
const int INF = 2e9 + 3;
const int MOD = 1000000;
int N;
int num[2];
struct SplayTree{
int val[MAX_N];
int ch[MAX_N][2];
int pre[MAX_N];
int Siz;
int rt;
inline void NewNode(int y,int &x,int v){
x = ++Siz;
pre[x] = y;
ch[x][0] = ch[x][1] = 0;
val[x] = v;
}
void Init(){
Siz = 0;
rt = 0;
NewNode(0,rt,-INF);
NewNode(rt,ch[rt][1],INF);
}
inline void Rotate(int x,int d){
int y = pre[x];
ch[y][d^1] = ch[x][d];
pre[ch[x][d]] = y;
pre[x] = pre[y];
if (pre[x])
ch[pre[y]][ch[pre[y]][1] == y] = x;
ch[x][d] = y;
pre[y] = x;
}
void Insert(int v){
int x = rt;
while(ch[x][val[x] < v])
x = ch[x][val[x] < v];
NewNode(x,ch[x][val[x] < v],v);
Splay(x,0);
}
inline void Splay(int x,int goal){
while(pre[x] != goal){
if (pre[pre[x]] == goal){
if (ch[pre[x]][0] == x){
Rotate(x,1);
}else
Rotate(x,0);
}else {
int y = pre[x];
int z = pre[y];
if (ch[z][0] == y){
if (ch[y][0] == x){
Rotate(y,1);
Rotate(x,1);
}else {
Rotate(x,0);
Rotate(x,1);
}
}else {
if (ch[y][1] == x){
Rotate(y,0);
Rotate(x,0);
}else{
Rotate(x,1);
Rotate(x,0);
}
}
}
}
if (goal == 0) rt = x;
}
inline int F_min(int v){
int x = rt;
int ans = INF;
while(x){
if (val[x]== v) return v;
if (val[x] > v) ans = min(ans,val[x]);
if (val[x] > v) x = ch[x][0];
else x = ch[x][1];
}
return ans;
}
inline int F_max(int v){
int x = rt;
int ans = -INF;
while(x){
if (val[x] == v) return v ;
if (val[x] < v) ans = max(ans,val[x]);
if (val[x] < v) x = ch[x][1];
else x = ch[x][0];
}
return ans;
}
inline int F_root(int v){
int x = rt;
while(x){
if (val[x] == v) return x;
if (val[x] > v) x = ch[x][0];
else x = ch[x][1];
}
return 0;
}
inline void DeleteNode(int x){ // 删除的时候先将该节点转到根,然后找右子树中最小的元素
Splay(x,0); // 令其为x的右儿子,这样删除该节点的时候只要将该节点的左子树
int tmp = ch[rt][1]; // 接在tmp的左子树上就ok了.
while(ch[tmp][0]){
tmp = ch[tmp][0];
}
Splay(tmp,x);
ch[tmp][0] = ch[x][0];
pre[ch[x][0]] = tmp;
pre[tmp] = 0;
rt = tmp;
}
}spt;
void input(){
num[0] = num[1] = 0;
spt.Init();
int ans = 0;
For(i,1,N,1){
int a,b;
scanf("%d%d",&a,&b);
if (num[!a] == 0){
num[a]++;
spt.Insert(b);
}else {
int minv = spt.F_min(b);
int maxv = spt.F_max(b);
ans = (ans + min(b - maxv,minv - b)) % MOD;
if (b - maxv <= minv - b)
spt.DeleteNode(spt.F_root(maxv));
else
spt.DeleteNode(spt.F_root(minv));
num[!a]--;
}
}
printf("%d\n",ans);
}
int main(){
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
while(scanf("%d",&N)!=EOF){
input();
}
}
大视野 1208 Splay 初步
最新推荐文章于 2016-09-11 15:53:52 发布