-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount_Of_Range_Sum.cpp
More file actions
64 lines (63 loc) · 1.71 KB
/
Count_Of_Range_Sum.cpp
File metadata and controls
64 lines (63 loc) · 1.71 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
typedef long int ll;
class Solution {
public:
struct Tree{
ll start,end;
int count;
Tree* left;
Tree* right;
Tree(ll s, ll e, int cnt){
start = s;
end = e;
count = cnt;
left = right = NULL;
}
};
Tree* build(vector<ll> &sum, int start, int end){
Tree* root = new Tree(sum[start],sum[end],0);
if(start==end)
return root;
int mid = (start+end)/2;
root->left = build(sum,start,mid);
root->right = build(sum,mid+1,end);
return root;
}
int query(Tree* root, ll start, ll end){
if(!root || end<root->start || start>root->end)
return 0;
if(start<=root->start && end>=root->end)
return root->count;
return (query(root->left,start,end)+query(root->right,start,end));
}
void update(Tree* root, ll val){
if(!root || val<root->start || val>root->end)
return;
root->count++;
if(root->start==root->end)
return;
update(root->left,val);
update(root->right,val);
return;
}
int countRangeSum(vector<int>& nums, int lower, int upper) {
if(nums.empty())
return 0;
set<ll> st;
ll tmp = 0;
for(auto& n: nums){
tmp += n;
st.insert(tmp);
}
vector<ll> sum;
for(auto& s:st)
sum.push_back(s);
Tree* root = build(sum,0,sum.size()-1);
int count = 0;
for(int i=nums.size()-1; i>=0; i--){
update(root,tmp);
tmp -= nums[i];
count += query(root,lower+tmp, upper+tmp);
}
return count;
}
};