Jayakrishna14

Ranking Books Q1

Sep 16th, 2025
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int floor(vector<int>& arr,int k,int n){
  4.     // functions searches an index i such that arr[i] <= k
  5.     // it is called floor
  6.  
  7.     if(k < arr[n - 1]) return n; // edge case handled
  8.     // edge case explanation:
  9.     // ex:
  10.     // indices: 0   1  2  3  4
  11.     // array:   100 50 40 20 10
  12.     // the index that suits for 5 in above array at index 5 i.e., the size of array.
  13.  
  14.  
  15.     int l=0,hi=n-1;
  16.     int ans = 0;
  17.     while(l<=hi){
  18.         int mid=(l+hi)/2;
  19.         if(arr[mid]>k){
  20.             l=mid+1;
  21.         }
  22.         else{
  23.             ans = mid;
  24.             hi=mid-1;
  25.         }
  26.     }
  27.     return ans; // returns the index where the book is suitable
  28. }
  29.  
  30. void removeDuplicates(vector<int>& arr) {
  31.     int n = arr.size();
  32.  
  33.     int i = 0, j = 0;
  34.     while(j < n) {
  35.         int cur = arr[j];
  36.         while(j < n && arr[j] == cur) {
  37.             j++;
  38.         }
  39.         arr[i] = cur;
  40.         i++;
  41.     }
  42.  
  43.     int toRemove = n - i;
  44.     while(toRemove-- > 0) {
  45.         arr.pop_back();
  46.     }
  47.  
  48. }
  49.  
  50. int main() {
  51.     int t;
  52.     cin>>t;
  53.     while(t--){
  54.         int n;
  55.         cin>>n;
  56.         vector<int> arr1(n);
  57.         for(int i=0;i<n;i++){
  58.             cin>>arr1[i];
  59.         }
  60.  
  61.         removeDuplicates(arr1); // function removes the duplicates from the reverse sorted array
  62.         n = arr1.size(); // new size of the array
  63.  
  64.         int m;
  65.         cin>>m;
  66.         vector<int> arr2(m);
  67.         for(int i=0;i<m;i++){
  68.             cin>>arr2[i];
  69.         }  
  70.         int f;
  71.         for(int i=0;i<m;i++){
  72.            // int f=ceil(arr1,arr2[i],n);
  73.            int f = floor(arr1, arr2[i], n);  // changed from ceil to floor
  74.            int rank = f + 1;
  75.            cout<< rank << " ";
  76.  
  77.         }
  78.         cout<<endl;
  79.     }
  80.     return 0;
  81.    
  82. }
Advertisement
Add Comment
Please, Sign In to add comment