/*
把A数组各个数字出现的次数放进线段树里,然后每次查询 0到A[i] - 1的个数,就是小于A[i]的个数
*/
class Solution {
public:
/*
* @param A: An integer array
* @param queries: The query list
* @return: The number of element in the array that are smaller that the given integer
*/
//const int inf = -0x3f3f3f3f;
class SegmentTree{
public:
SegmentTree* left;
SegmentTree* right;
int start;
int end;
int sum;
SegmentTree(int start, int end, int sum){
this -> start = start;
this -> end = end;
this -> left = NULL;
this -> right = NULL;
this -> sum = sum;
}
};
int build(SegmentTree* &root, int left, int right, vector<int> &st){
if(left > right) return 0;
root -> start = left;
root -> end = right;
if(left == right) root -> sum = st[left];
else {
int mid = (left + right) / 2;
root -> left = new SegmentTree(left, mid, 0);
root -> right = new SegmentTree(mid+1, right, 0);
root -> sum = build(root -> left, left, mid, st) + build(root -> right, mid + 1, right, st);
}
return root -> sum;
}
int query(SegmentTree* &root, int left, int right){
if(root == NULL || left > right) return 0;
if(left <= root -> start && root -> end <= right){
return root -> sum;
}
int mid = (root -> start + root -> end) / 2;
if(left > mid){
return query(root -> right, left, right);
} else if(right <= mid){
return query(root -> left, left, right);
} else {
return query(root -> left, left, mid) + query(root -> right, mid+1, right);
}
}
vector<int> countOfSmallerNumber(vector<int> A, vector<int> queries) {
// write your code here
vector<int> ans;
if(A.size() == 0){
for(int i = 0; i < queries.size(); ++i){
ans.push_back(0);
}
return ans;
}
sort(A.begin(), A.end());
vector<int> st;
st.resize(A[A.size() - 1] + 10, 0);
for(int i = 0; i < A.size(); ++i){
st[A[i]] += 1;
}
SegmentTree* root = new SegmentTree(0, 0, 0);
build(root, 0, A[A.size() - 1], st);
for(int i = 0; i < queries.size(); ++i){
int tmp = query(root, 0, queries[i] - 1);
ans.push_back(tmp);
}
delete(root);
return ans;
}
};