/* Creating a segment tree. Then with the query()
we can easily find the sum of any segment of the tree.
*/
#include<bits/stdc++.h>
using namespace std;
#define mx 100001
#define fi(a, b) for(int i=a; i<=b; i++)
#define fd(a, b) for(int i=a; i>=b; i--)
int n, m, ar[mx], tree[mx*3], ii, jj;
void segmentt(int node, int st, int en){
if(st==en){
tree[node]=ar[st];
return ;
}
int left=node*2;
int right=node*2+1;
int mid=(st+en)/2;
segmentt(left, st, mid);
segmentt(right, mid+1, en);
tree[node]=tree[left]+tree[right];
}
int query(int node, int st, int en){
if(ii<=st && jj>=en) return tree[node]; // relevant segment
else if(ii>en || jj<st) return 0; // out of the segment
else{ // needs to divide again
int left=2*node, right=node*2+1, mid=(st+en)/2;
return (query(left, st, mid) + query(right, mid+1, en));
}
}
int main(){
cin>>n;
fi(1, n)
cin>>ar[i];
segmentt(1, 1, n);
cin>>m;
fi(1, m){
cin>>ii>>jj;
cout<<query(1, 1, n)<<endl;
}
return 0;
}
|
Thursday, October 19, 2017
Implementation of Segment Tree
Subscribe to:
Post Comments (Atom)
-
#include<bits/stdc++.h> #define ll long long using namespace std ; ll n , k , t_case ; ll bigmod ( ll b , ll p , ll m...
-
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 ...
-
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 3...
No comments:
Post a Comment