-
Notifications
You must be signed in to change notification settings - Fork 438
/
Persistent-Array.cpp
123 lines (114 loc) · 1.66 KB
/
Persistent-Array.cpp
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
#include <cstdio>
#define NIL 0
#define ELEMENT_COUNT 100000
#define EDITION_COUNT 100000
#define POOL_SIZE 1000000
using namespace std;
struct node
{
node *lch, *rch;
int v;
node(int _v = 0) : v(_v) { lch = rch = NIL; }
void* operator new (size_t);
}*root[EDITION_COUNT], pool[POOL_SIZE];
int top = 0;
int n, d[ELEMENT_COUNT], cur = 0, used = 1;
void* node::operator new (size_t)
{
return pool + top++;
}
void build(node *&u, int l, int r)
{
u = new node;
if (l == r)
{
u->v = d[l];
}
else
{
int mid = (l + r) >> 1;
build(u->lch, l, mid);
build(u->rch, mid + 1, r);
}
}
void modify(node *&u, node *old, int l, int r, int k, int v)
{
u = new node;
if (l == r)
{
u->v = v;
}
else
{
int mid = (l + r) >> 1;
if (k <= mid)
{
u->rch = old->rch;
modify(u->lch, old->lch, l, mid, k, v);
}
else
{
u->lch = old->lch;
modify(u->rch, old->rch, mid + 1, r, k, v);
}
}
}
int query(node *u, int l, int r, int k)
{
if (l == r)
{
return u->v;
}
else
{
int mid = (l + r) >> 1;
if (k <= mid)
{
return query(u->lch, l, mid, k);
}
else
{
return query(u->rch, mid + 1, r, k);
}
}
}
int main()
{
int op, e, k, x;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &d[i]);
}
build(root[cur], 1, n);
while (true)
{
scanf("%d", &op);
if (op == 1)
{
scanf("%d%d", &k, &x);
modify(root[used], root[cur], 1, n, k, x);
cur = used;
used++;
}
else if (op == 2)
{
scanf("%d%d", &e, &k);
printf("%d\n", query(root[e], 1, n, k));
}
else if (op == 3)
{
scanf("%d", &e);
cur = e;
}
else if (op == 0)
{
break;
}
else
{
printf("No such command!\n");
}
}
return 0;
}