Skip to content

Commit d43ff50

Browse files
authored
仅支持单点修改的可持久化线段树(未验证正确性)
1 parent d776d17 commit d43ff50

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed

Persistent-Segment-Tree(Sum).cpp

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
#include <cstdio>
2+
3+
#define ELEMENT_COUNT 100000
4+
#define EDITION_COUNT 100000
5+
6+
using namespace std;
7+
8+
struct node
9+
{
10+
int l, r, sum;
11+
node *lch, *rch;
12+
}*root[EDITION_COUNT];
13+
14+
int n, d[ELEMENT_COUNT], hs = 0;
15+
16+
void build(int l, int r, node *u)
17+
{
18+
u->l = l;
19+
u->r = r;
20+
if (l == r)
21+
{
22+
u->sum = d[l];
23+
}
24+
else
25+
{
26+
int mid = (l + r) >> 1;
27+
build(l, mid, u->lch = new node);
28+
build(mid + 1, r, u->rch = new node);
29+
u->sum = u->lch->sum + u->rch->sum;
30+
}
31+
}
32+
33+
int query(int l, int r, node *u)
34+
{
35+
if (u->l == l && u->r == r)
36+
{
37+
return u->sum;
38+
}
39+
else
40+
{
41+
int mid = (u->l + u->r) >> 1;
42+
if (r <= mid)
43+
{
44+
return query(l, r, u->lch);
45+
}
46+
else if (l > mid)
47+
{
48+
return query(l, r, u->rch);
49+
}
50+
else
51+
{
52+
return query(l, mid, u->lch) + query(mid + 1, r, u->rch);
53+
}
54+
}
55+
}
56+
57+
void modify(int k, int v, node *u, node *ori)
58+
{
59+
u->l = ori->l;
60+
u->r = ori->r;
61+
if (u->l == u->r)
62+
{
63+
u->sum = v;
64+
}
65+
else
66+
{
67+
int mid = (u->l + u->r) >> 1;
68+
if (k <= mid)
69+
{
70+
u->rch = ori->rch;
71+
u->lch = new node;
72+
modify(k, v, u->lch, ori->lch);
73+
}
74+
else
75+
{
76+
u->lch = ori->lch;
77+
u->rch = new node;
78+
modify(k, v, u->rch, ori->rch);
79+
}
80+
u->sum = u->lch->sum + u->rch->sum;
81+
}
82+
}
83+
84+
int main()
85+
{
86+
scanf("%d", &n);
87+
for (int i = 1; i <= n; i++)
88+
{
89+
scanf("%d", &d[i]);
90+
}
91+
build(1, n, root[0] = new node);
92+
int in, edition, ql, qr, k, v;
93+
while (true)
94+
{
95+
scanf("%d", &in);
96+
if (in == 1)
97+
{
98+
scanf("%d%d%d", &edition, &ql, &qr);
99+
printf("%d\n", query(ql, qr, root[edition]));
100+
}
101+
else if (in == 2)
102+
{
103+
scanf("%d%d", &k, &v);
104+
hs++;
105+
modify(k, v, root[hs] = new node, root[hs - 1]);
106+
}
107+
else if (in == 3)
108+
{
109+
printf("Current edition : %d\n", hs);
110+
}
111+
else if (in == 0)
112+
{
113+
return 0;
114+
}
115+
else
116+
{
117+
printf("No such command!\n");
118+
}
119+
}
120+
return 0;
121+
}

0 commit comments

Comments
 (0)