-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegment tree
More file actions
88 lines (58 loc) · 1.29 KB
/
segment tree
File metadata and controls
88 lines (58 loc) · 1.29 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
using namespace std;
int create(int l,int r,int at,int ars[],int arr[])
{
if(l==r)
{
ars[at]=arr[l];
return 0;
}
create(l,(l+r)/2,at*2,ars,arr);
create((l+r)/2+1,r,at*2+1,ars,arr);
ars[at]=ars[at*2]+ars[at*2+1];
}
int query(int at,int L,int R,int l,int r,int ars[])
{
if(l>R||r<L)
return 0;
if(L==l&&R==r)
return ars[at];
int x=query(at*2,L,(L+R)/2,l,r,ars);
int y=query(at*2+1,(L+R)/2+1,R,l,r,ars);
return x+y;
}
int update(int at,int value,int position,int l,int r,int arr[],int ars[])
{
if(l==r&&l==position)
{
arr[l]=value;
ars[at]=value;
return 0;
}
int mid=(l+r)/2;
if(position<=mid)
update(at*2,value,position,l,mid,arr,ars);
else
update(at*2+1,value,position,mid+1,r,arr,ars);
ars[at]=ars[at*2]+ars[at*2+1];
}
int main() {
int n;
cin>>n;
int arr[n+3]={},ars[n*4]={};
for(int x=1;x<=n;x++)
{
cin>>arr[x];
}
create(1,n,1,ars,arr);
int start,end;
cout<<"enter range you want to sum"<<endl;
cin>>start>>end;
cout<<"result is: "<<query(1,1,n,start,end,ars)<<endl;
int value,position;
cout<<"enter value and position you want to change: "<<endl;
cin>>value>>position;
update(1,value,position,1,5,arr,ars);
cout<<"after update result is: "<<query(1,1,n,start,end,ars)<<endl;
return 0;
}