-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathSegmentTree.cpp
91 lines (81 loc) · 1.42 KB
/
SegmentTree.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
// segment tree implementation
#include<bits/stdc++.h>
using namespace std;
int create(int s[],int i,int a[],int l,int r,int &m)
{
if(l==r)
{
if(a[l]>m){
s[i]=1;
m=a[l];
}
else
{
s[i]=0;
}
return s[i];
}
else{
int mid=(l+r)/2;
s[i]=create(s,2*i+1,a,l,mid,m)+create(s,2*i+2,a,mid+1,r,m);
return s[i];
}
}
int sum(int s[],int i,int ql,int qr,int l,int r)
{
if(l>=ql && qr>=r)
{
return s[i];
}
else if(r<ql || l>qr)
{
return 0;
}
else
{
int mid=(l+r)/2;
return sum(s,2*i+1,ql,qr,l,mid)+sum(s,2*i+2,ql,qr,mid+1,r);
}
}
void update(int s[],int pos,int diff,int i,int l,int r)
{
if(pos>=l && pos<=r)
{
s[i]=s[i]+diff;
if(l!=r)
{
int mid=(l+r)/2;
update(s,pos,diff,2*i+1,l,mid);
update(s,pos,diff,2*i+2,mid+1,r);
}
}
return ;
}
void print(int a[],int n)
{
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
int arr[n];
int d=0;
while(d<n)
{
cin>>arr[d];
d++;
}
int x=int(ceil(log2(n)));
int size=2*(int)pow(2, x) - 1;
cout<<size<<endl;
int S[size]={0};
int m=0;
create(S,0,arr,0,n-1,m);
print(S,size);
cout<<sum(S,0,0,n-1,0,n-1)<<endl;
}