Recently I was working on a problem and I could not solve it within time constraints. The question is as follows:
Problem:
Bob currently has N empty stacks numbered from 1 to N. He does the following M times: Select 2 two numbers L and R and add one stone to each of the stacks [L,L+1,...R] At the end of these M operations, he would like to answer Q queries: How many of the stacks have at least H stones in them?
Input Format
First line contains N - number of stacks.
Second line contains M - number of operations.
Each of the next M lines consists of two space separated integers L and R.
Followed by integer Q - number of queries.
Each of next Q lines contain a single integer H.
Constraints: 1 ≤ N ≤ 1000000, 1 ≤ M ≤ 1000000, 1 ≤ L ≤ R ≤ N, 1 ≤ Q ≤ 1000000, 1 ≤ H ≤ N,
My approach was as follows:
int main(){
    int n, m, l, r, q, h;
    cin >> n >> m;
    
    vector<int>nums(n,0);
    // processing vector based on instructions
    for(int i=0; i<m; i++){
        cin >> l >> r; 
        for(int j=l-1; j<r; j++)
            nums[j]++;
    }
    //storing freq in map
    map<int, int, greater<int>>count;
    for(auto x: nums)
        count[x]++;
   
    // getting no. of queries
    cin >> q;
    vector<pair<int, int>>queries(q);
    for(int i=0; i<q; i++){
        cin >> h;//query height
        queries[i] = make_pair(h, i);
    }
    
    sort(queries.begin(), queries.end(), greater<int>());
    
    vector<int> res(q,0);
    
    int q_index=0;
    int c = 0;
    for(auto&[key, val]:count){
        while(k<q && key < queries[q_index].first){
            res[queries[q_index].second] = c;
            q_index++;
        }
        c+=val;
        if(k == q){
            break;
        }
    }
    
    for(int x: res)cout << x << endl;
    return 0;
}
This works but fails for large test cases. What should be the approach to solve problems like these? TIA!
 
     
    