Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- // kth largest element in a 2d array sorted row-wise and column-wise
- #include<bits/stdc++.h>
- using namespace std;
- #define MAX 1000
- int mat[MAX][MAX];
- int kthSmallest(int mat[MAX][MAX], int n, int k);
- // driver program to test above function
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- for(int i=0;i<n;i++)
- for(int j=0;j<n;j++)
- cin>>mat[i][j];
- int r;
- cin>>r;
- cout<<kthSmallest(mat,n,r)<<endl;
- }
- // cout << "7th smallest element is " << kthSmallest(mat, 4, 7);
- return 0;
- }
- // } Driver Code Ends
- int kthSmallest(int mat[MAX][MAX], int n, int k)
- {
- //Your code here
- int min = 1, max =10000, mid, pos=0;
- int p = std::min(k, n);
- while(min<max)
- {
- mid = (min+max)/2;
- pos=0;
- for(int i=0;i<p;i++)
- pos += upper_bound(mat[i], mat[i] + n, mid) - mat[i];
- if(pos<k)
- min = mid+1;
- else max = mid;
- }
- return min;
- }
Advertisement
Add Comment
Please, Sign In to add comment