forked from sandeepshahi/Codes-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegment.cpp
56 lines (48 loc) · 783 Bytes
/
segment.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
#include<bits/stdc++.h>
using namespace std;
void segtree(vector<int> &seg,int n)
{
for(int i=n-1;i>0;i--)
{
seg[i]=seg[i<<1]+seg[i<<1|1];
}
}
int query(vector<int> seg,int a,int b,int n)
{ int s=0;
a+=n;
b+=n;
while(a<=b)
{
if(a&1)
{
s+=seg[a++];
}
if(!(b&1))
{
s+=seg[b--];
}
a>>=1;
b>>=1;
}
return s;
}
int main()
{
int n;
cout<<"Enter N\n";
cin>>n;
vector<int> v;
vector<int> seg(2*n);
int a;
for(int i=0;i<n;i++)
{
cin>>a;
v.push_back(a);
seg[i+n]=v[i];
}
segtree(seg,n);
cout<<"Enter range\n";
int l,r;
cin>>l>>r;
cout<<query(seg,l,r,n);
}