Can anyone debug the code

Revision en1, by Psychotic_D_BKL, 2025-01-13 12:23:20

https://www.spoj.com/problems/KQUERY/

this was the question and my code is

include<bits/stdc++.h>

using namespace std;

define int long long

int n; vector<vector> segmentTree; vector a; //we are making a merge sort tree here

void built(int l , int r, int index){ if(l==r){ segmentTree[index].push_back(a[l]); return; } int mid=l+(r-l)/2; built(l,mid,2*index+1); built(mid+1,r,2*index+2); segmentTree[index].clear(); int i=0,j=0; while(i<segmentTree[2*index+1].size() && j<segmentTree[2*index+2].size()){ if(segmentTree[2*index+1][i]<segmentTree[2*index+2][j]){ segmentTree[index].push_back(segmentTree[2*index+1][i]); i++; }else{ segmentTree[index].push_back(segmentTree[2*index+2][j]); j++; } } while(i<segmentTree[2*index+1].size()){ segmentTree[index].push_back(segmentTree[2*index+1][i]); i++; } while(j<segmentTree[2*index+2].size()){ segmentTree[index].push_back(segmentTree[2*index+2][j]); j++; }

}

int query(int l, int r, int start, int end, int index, int k) { if (l > end || r < start) { return 0; } if (l >= start && r <= end) { return segmentTree[index].size() — (upper_bound(segmentTree[index].begin(), segmentTree[index].end(), k) — segmentTree[index].begin()); } int mid = l + (r — l) / 2; return query(l, mid, start, end, 2 * index + 1, k) + query(mid + 1, r, start, end, 2 * index + 2, k); }

int32_t main(){ cin>>n; segmentTree.resize(4*n); a.resize(n); for(int i=0;i<n;i++){ cin>>a[i]; } built(0,n-1,0);

int q;
cin>>q;
while(q--){
    int l,r,k;
    cin>>l>>r>>k;
    cout<<query(0,n-1,l-1,r-1,0,k)<<endl;
}

}

can anyone tell me why am i getting tle..

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English Psychotic_D_BKL 2025-01-13 12:27:09 1480
en1 English Psychotic_D_BKL 2025-01-13 12:23:20 1994 Initial revision (published)