jayati

Number of pairs

Dec 5th, 2023
913
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial template for C++
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. // } Driver Code Ends
  8. //User function template for C++
  9.  
  10. class Solution{  
  11. public:
  12.     int count(int x, int Y[], int n, int NoOfY[])
  13.     {
  14.        
  15.         if (x == 0)
  16.             return 0;
  17.    
  18.         if (x == 1)
  19.             return NoOfY[0];
  20.      
  21.        
  22.         int* idx = upper_bound(Y, Y + n, x);
  23.         int ans = (Y + n) - idx;
  24.      
  25.  
  26.         ans += (NoOfY[0] + NoOfY[1]);
  27.      
  28.        
  29.         if (x == 2)
  30.             ans -= (NoOfY[3] + NoOfY[4]);
  31.      
  32.      
  33.         if (x == 3)
  34.             ans += NoOfY[2];
  35.      
  36.         return ans;
  37.     }
  38.     long long countPairs(int X[], int Y[], int m, int n) {
  39.          int NoOfY[5] = { 0 };
  40.     for (int i = 0; i < n; i++)
  41.         if (Y[i] < 5)
  42.             NoOfY[Y[i]]++;
  43.  
  44.     // Sort Y[] so that we can do binary search in it
  45.     sort(Y, Y + n);
  46.  
  47.     long long total_pairs = 0; // Initialize result
  48.  
  49.     // Take every element of X and count pairs with it
  50.     for (int i = 0; i < m; i++)
  51.         total_pairs += count(X[i], Y, n, NoOfY);
  52.  
  53.     return total_pairs;
  54.         // code here
  55.     }
  56. };
  57.  
  58. //{ Driver Code Starts.
  59.  
  60. int main() {
  61.     int t;
  62.     cin >> t;
  63.     while (t--) {
  64.         int m, n;
  65.         cin >> m >> n;
  66.         int X[m], Y[n];
  67.         for (int i = 0; i < m; i++) {
  68.             cin >> X[i];
  69.         }
  70.         for (int i = 0; i < n; i++) {
  71.             cin >> Y[i];
  72.         }
  73.         Solution ob;
  74.         auto ans = ob.countPairs(X, Y, m, n);
  75.         cout << ans << "\n";
  76.     }
  77.     return 0;
  78. }
  79. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment