Untitled
unknown
plain_text
10 months ago
3.0 kB
3
Indexable
// This segment tree would give kth smallest element in any subarray of [l,r] you can search on gfg // Declaring a global segment tree vector<ll> seg[4*N]; // Function to build the merge sort // segment tree of indices void build(ll ci, ll st, ll end, pair<ll, ll>* B) { if (st == end) { // Using second property of B seg[ci].push_back(B[st].second); return; } ll mid = (st + end) / 2; build(2 * ci + 1, st, mid, B); build(2 * ci + 2, mid + 1, end, B); // Inbuilt merge function // this takes two sorted arrays and merge // them into a sorted array merge(seg[2 * ci + 1].begin(), seg[2 * ci + 1].end(), seg[2 * ci + 2].begin(), seg[2 * ci + 2].end(), back_inserter(seg[ci])); } // Function to return the index of // kth smallest element in range [l, r] ll query(ll ci, ll st, ll end, ll l, ll r, ll k) { // Base case if (st == end) return seg[ci][0]; // Finding value of 'p' as described in article // seg[2*ci+1] is left node of seg[ci] ll p = upper_bound(seg[2 * ci + 1].begin(), seg[2 * ci + 1].end(), r) - lower_bound(seg[2 * ci + 1].begin(), seg[2 * ci + 1].end(), l); ll mid = (st + end) / 2; if (p >= k) return query(2 * ci + 1, st, mid, l, r, k); else return query(2 * ci + 2, mid + 1, end, l, r, k - p); } void solve(){ ll k ; cin>>k; ll n ; cin>>n; vector<pair<ll,ll>> p(n); // patience array vector<ll> pp(n); // stores the sorted patience for lower_bound vector<ll> idx(n); // stores the indices of sorted array forsn(i,0,n){ cin>>p[i].f; pp[i] = p[i].f; p[i].s = i ; } ll g; cin>>g; vector<ll> q(g); input(q); sort(all(p)); sort(all(pp)); forsn(i,0,n) idx[i] = p[i].s+1; // Learn how to build seg_tree from gfg , currently building on indices pair<ll,ll> B[n]; forsn(i,0,n) B[i] = {idx[i],i}; sort(B,B+n); build(0,0,n-1,B); forsn(i,0,g){ ll j = lower_bound(all(pp),q[i])-pp.begin(); // check the position where the passengers patience >= q[i] if(j == n){ cout<<0<<ln; } else{ // Remember that we have sorted the queue , so destroyed the queue DS. So searching for kth smallest index passenger from j=< i <= n-1 if(j + k-1 < n) cout<<idx[query(0,0,n-1,j,n-1,k)]<<ln; else cout<<0<<ln; } } } int main() { fast_cin(); ll t=1; // ll t; // cin>>t/; cout<<fixed<<setprecision(0); while (t--) { solve(); } return 0; }
Editor is loading...
Leave a Comment