-
Notifications
You must be signed in to change notification settings - Fork 7
/
PersistentSegmentTree.cpp
131 lines (98 loc) · 2.09 KB
/
PersistentSegmentTree.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
#include <iostream>
using namespace std;
int a[]={5,9,1,2,3};
// Structure of nodes of tree
struct node
{
int val;
node *left,*right;
node()
{
}
node(node *l,node *r,int v)
{
left=l;
right=r;
val=v;
}
};
//array to store versions
node *version[3];
//function to build version 0
void build(node *n,int low, int high)
{
cout<<"Array: ";
for (int i = low; i <= high; ++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
if(low==high)
{
n->val=a[low];
return;
}
int mid=(low+high)/2;
n->left= new node(NULL,NULL,0);
n->right= new node(NULL,NULL,0);
build(n->left,low,mid);
build(n->right,mid+1,high);
n->val= n->left->val + n->right->val;
}
//function to make other version(to update previous version)
void update(node *prev, node *cur, int low, int high, int idx, int value)
{
if(idx>high || idx<low || low>high)
return;
if(low==high)
{
cur->val=value;
return;
}
int mid=(low+high)/2;
if(idx<=mid)
{
cur->right=prev->right;
cur->left= new node(NULL,NULL,0);
update(prev->left,cur->left,low,mid,idx,value);
}
else
{
cur->left=prev->left;
cur->right= new node(NULL,NULL,0);
update(prev->right,cur->right,mid+1,high,idx,value);
}
cur->val = cur->left->val + cur->right->val;
}
//For query
int query(node *n, int low, int high, int l, int r)
{
if(l>high || r<low || low>high)
{
return 0;
}
if(l<=low && r>=high)
{
return n->val;
}
int mid=(low+high)/2;
int x= query(n->left, low, mid, l, r);
int y= query(n->right, mid+1, high, l, r);
return x+y;
}
//driver function
int main()
{
int n= sizeof(a)/sizeof(a[0]);
node *root= new node(NULL,NULL,0);
build(root,0,n-1);
version[0]=root;
version[1]=new node(NULL,NULL,0);
update(version[0],version[1],0,n-1,3,1);
version[2]=new node(NULL,NULL,0);
update(version[1],version[2],0,n-1,4,8);
cout << "In version 0 , the sum in range(0,2) is " << query(version[0], 0, n-1, 0, 2) << endl;
cout << "In version 1 ,the sum in range(1,3) is "<< query(version[1], 0, n-1, 1, 3) << endl;
cout << "In version 2 , the sum in range(1,4) is "<< query(version[2], 0, n-1, 1, 4) << endl;
return 0;
}