-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPST.cpp
139 lines (112 loc) · 2.41 KB
/
PST.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
template<typename T>
class PST
{
struct Node
{
int lidx, ridx;
T value;
Node() :value(T()), lidx(-1), ridx(-1) {}
};
public:
class iterator
{
public:
iterator(PST<T>& p, int n)
: pst(p), node(n) {}
iterator& operator=(const iterator& other)
{
assert(&pst == &other.pst);
node = other.node;
return *this;
}
T get() const
{
return pst.node[node].value;
}
iterator left() const
{
return iterator(pst, pst.node[node].lidx);
}
iterator right() const
{
return iterator(pst, pst.node[node].ridx);
}
private:
PST<T>& pst;
int node;
};
template<typename M>
PST(int n_, const M& m) : n(n_), merge(m) {}
iterator it(int r)
{
return iterator(*this, root[r]);
}
int rmost() const
{
return n;
}
int update(int idx, const T& value)
{
return update((int)root.size() - 1, idx, value);
}
int update(int pre, int idx, const T& value)
{
root.emplace_back(_update(root[pre], idx, value, 0, n));
return (int)root.size() - 1;
}
T query(int k, int start, int end)
{
return _query(root[k], start, end, 0, n);
}
void init()
{
root.push_back(init(0, n));
}
private:
int init(int start, int end)
{
int idx = node.size();
node.emplace_back();
if (start != end)
{
int mid = (start + end) / 2;
node[idx].lidx = init(start, mid);
node[idx].ridx = init(mid + 1, end);
}
return idx;
}
int _update(int prev, int idx, const T& value, int start, int end)
{
if (idx < start || idx > end)
return prev;
int nidx = node.size();
node.emplace_back();
if (start == end)
node[nidx].value = value;
else
{
int mid = (start + end) / 2;
node[nidx].lidx = _update(node[prev].lidx, idx, value, start, mid);
node[nidx].ridx = _update(node[prev].ridx, idx, value, mid + 1, end);
node[nidx].value = merge(node[node[nidx].lidx].value, node[node[nidx].ridx].value);
}
return nidx;
}
T _query(int idx, int start, int end, int left, int right)
{
if (start <= left && right <= end)
return node[idx].value;
int mid = (left + right) / 2;
if (mid + 1 > end)
return _query(node[idx].lidx, start, end, left, mid);
if (mid < start)
return _query(node[idx].ridx, start, end, mid + 1, right);
return merge(_query(node[idx].lidx, start, end, left, mid),
_query(node[idx].ridx, start, end, mid + 1, right));
}
using Merge = function<T(const T&, const T&)>;
Merge merge;
vector<int> root;
vector<Node> node;
int n;
};