Blog of RuSun

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

P2234 [HNOI2002]营业额统计

P2234 [HNOI2002]营业额统计

查询前驱后继即可,甚至可以 STL

查看代码
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
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 4e4 + 10, inf = 1e8;
int n, rt, idx;
struct Node
{
int v, p, sz, s[2];
void init (int a, int b)
{
v = a;
p = b;
}
}tr[N];
void pushup (int x)
{
tr[x].sz = tr[tr[x].s[0]].sz + tr[tr[x].s[1]].sz + 1;
}
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)
{
while (tr[x].p != k)
{
int y = tr[x].p, z = tr[y].p;
if (z != k)
if ((tr[y].s[1] == x) ^ (tr[z].s[1] == y))
rotate(x);
else
rotate(y);
rotate(x);
}
if (!k)
rt = x;
}
void insert (int v)
{
int u = rt, p = 0;
while (u)
{
p = u;
u = tr[u].s[v > tr[u].v];
}
u = ++idx;
if (p)
tr[p].s[v > tr[p].v] = u;
tr[u].init(v, p);
splay(u, 0);
}
int get_pre (int v)
{
int u = rt, res;
while (u)
if (tr[u].v == v)
return v;
else if (tr[u].v >= v)
{
res = tr[u].v;
u = tr[u].s[0];
}
else
u = tr[u].s[1];
return res;
}
int get_nxt (int v)
{
int u = rt, res;
while (u)
if (tr[u].v == v)
return v;
else if (tr[u].v < v)
{
res = tr[u].v;
u = tr[u].s[1];
}
else
u = tr[u].s[0];
return res;
}
int main ()
{
insert(inf);
insert(-inf);
scanf("%d", &n);
int res = 0;
for (int i = 1, a; i <= n; i++)
{
scanf("%d", &a);
if (i == 1)
res += a;
else
res += min(abs(get_pre(a) - a), abs(get_nxt(a) - a));
insert(a);
}
printf("%d", res);
return 0;
}