jayati

Kth element in Matrix

Dec 8th, 2023
835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // kth largest element in a 2d array sorted row-wise and column-wise
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5. #define MAX 1000
  6. int mat[MAX][MAX];
  7. int kthSmallest(int mat[MAX][MAX], int n, int k);
  8. // driver program to test above function
  9. int main()
  10. {
  11.     int t;
  12.     cin>>t;
  13.     while(t--)
  14.     {
  15.         int n;
  16.         cin>>n;
  17.    
  18.         for(int i=0;i<n;i++)
  19.             for(int j=0;j<n;j++)
  20.                 cin>>mat[i][j];
  21.         int r;
  22.         cin>>r;
  23.         cout<<kthSmallest(mat,n,r)<<endl;
  24.     }
  25.      // cout << "7th smallest element is " << kthSmallest(mat, 4, 7);
  26.       return 0;
  27. }
  28.  
  29. // } Driver Code Ends
  30.  
  31.  
  32.  
  33. int kthSmallest(int mat[MAX][MAX], int n, int k)
  34. {
  35.   //Your code here
  36.   int min = 1, max =10000, mid, pos=0;
  37.   int p = std::min(k, n);
  38.  
  39.  
  40.   while(min<max)
  41.   {
  42.       mid = (min+max)/2;
  43.  
  44.       pos=0;
  45.       for(int i=0;i<p;i++)
  46.         pos += upper_bound(mat[i], mat[i] + n, mid) - mat[i];
  47.  
  48.       if(pos<k)
  49.         min = mid+1;
  50.      
  51.       else max = mid;
  52.   }  
  53.  
  54.   return min;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment