-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegmenttree.js
More file actions
73 lines (73 loc) · 1.73 KB
/
segmenttree.js
File metadata and controls
73 lines (73 loc) · 1.73 KB
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
class segment{
constructor(data){
this.data=[data];
}
insert(data){
this.data.push(data);
let i=this.data.length-1;
while(i>0){
let j=Math.floor((i-1)/2);
this.data[j]+=this.data[i];
i=j;
}
}
display(){
console.log(this.data);
}
sumat(l,r){
let sum=0;
l+=this.data.length/2;
r+=this.data.length/2;
while(l<=r){
if(l%2==1){
sum+=this.data[l];
l++;
}
if(r%2==0){
sum+=this.data[r];
r--;
}
l=Math.floor(l/2);
r=Math.floor(r/2);
}
return sum;
}
update(newdata,prvsdata){
let i=this.data.indexOf(prvsdata);
this.data[i]=newdata;
while(i>0){
let j=Math.floor((i-1)/2);
this.data[j]-=prvsdata;
this.data[j]+=newdata;
i=j;
}
}
delete(data){
let i=this.data.indexOf(data);
this.data[i]=this.data[this.data.length-1];
this.data.pop();
while(i>0){
let j=Math.floor((i-1)/2);
this.data[j]-=data;
this.data[j]+=this.data[i];
i=j;
}
}
}
module.exports={
structure:segment,
description:"Segment Tree",
complexity:{
insert:"O(log n)",
delete:"O(log n)",
sumat:"O(log n)",
update:"O(log n)"
},
methods:{
insert:"Inserts an element into the segment tree",
delete:"Deletes an element from the segment tree",
sumat:"Returns the sum of elements from l to r",
update:"Updates the value of an element"
},
category:"Tree"
};