Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2286 [HNOI2004]宠物收养场

P2286 [HNOI2004]宠物收养场

维护两棵平衡树,求前驱后继即可。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long LL;
const int N = 8e4 + 10, mod = 1e6;
LL inf = 1 << 31;
int n, rt[2], idx;
struct Node
{
LL v;
int p, sz, cnt, s[2];
} tr[N];
void pushup(int x)
{
tr[x].sz = tr[tr[x].s[0]].sz + tr[tr[x].s[1]].sz + tr[x].cnt;
}
void rotate(int x)
{
int y = tr[x].p, z = tr[y].p;
int k = tr[y].s[1] == x;
tr[z].s[tr[z].s[1] == y] = x;
tr[x].p = z;
tr[y].s[k] = tr[x].s[k ^ 1];
tr[tr[x].s[k ^ 1]].p = y;
tr[x].s[k ^ 1] = y;
tr[y].p = x;
pushup(y);
pushup(x);
}
void splay(int x, int k, bool op)
{
while (tr[x].p != k)
{
int y = tr[x].p, z = tr[y].p;
if (z != k)
if ((tr[z].s[1] == y) ^ (tr[y].s[1] == x))
rotate(x);
else
rotate(y);
rotate(x);
}
if (!k)
rt[op] = x;
}
int pre(int x, bool op)
{
int u = rt[op], res;
while (u)
{
if (tr[u].v == x)
return u;
if (tr[u].v < x)
{
res = u;
u = tr[u].s[1];
}
else
u = tr[u].s[0];
}
return res;
}
int nxt(int x, bool op)
{
int u = rt[op], res;
while (u)
{
if (tr[u].v == x)
return u;
if (tr[u].v > x)
{
res = u;
u = tr[u].s[0];
}
else
u = tr[u].s[1];
}
return res;
}
void insert(int x, bool op)
{
int u = rt[op], p = 0;
while (u)
{
if (tr[u].v == x)
{
tr[u].cnt++;
splay(u, 0, op);
return;
}
p = u;
u = tr[u].s[x > tr[u].v];
}
u = ++idx;
if (p)
tr[p].s[x > tr[p].v] = u;
tr[u].p = p;
tr[u].v = x;
tr[u].cnt = 1;
splay(u, 0, op);
}
void init()
{
for (int op = 0; op < 2; op++)
{
tr[rt[op] = (++idx)].v = -inf;
tr[rt[op]].cnt = 1;
tr[rt[op]].sz = 1;
tr[rt[op]].p = 0;
insert(inf, op);
}
}
int main()
{
init();
scanf("%d", &n);
LL res = 0;
while (n--)
{
int a;
LL b;
scanf("%d%lld", &a, &b);
if (tr[rt[a]].sz < 3)
{
insert(b, a ^ 1);
continue;
}
int pos = pre(b, a), k = nxt(b, a);
if (tr[k].v - b < b - tr[pos].v)
pos = k;
res = (res + abs(tr[pos].v - b)) % mod;
tr[pos].cnt--;
splay(pos, 0, a);
if (!tr[pos].cnt)
{
int l = pre(tr[pos].v - 1, a), r = nxt(tr[pos].v + 1, a);
splay(l, 0, a);
splay(r, l, a);
tr[tr[r].s[0]].p = 0;
tr[r].s[0] = 0;
}
}
printf("%lld", res);
return 0;
}