PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000186. Phần tử nhỏ thứ K trong ma trận đã sắp xếp (Kth Smallest Element in a Sorted Matrix)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Phần tử nhỏ thứ K trong ma trận đã sắp xếp (Kth Smallest Element in a Sorted Matrix)

Kth Smallest Element in a Sorted Matrix

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an n×nn\times n integer matrix aa, with rows and columns numbered from 11 to nn. Every row is sorted in non-decreasing order from left to right, and every column is sorted in non-decreasing order from top to bottom. Values may repeat and may be negative.

Take all n2n^2 entries and sort them in non-decreasing order, counting equal entries from different cells separately. Return the value at the kk-th position, numbered from 11.

Input

  • The first line contains integers nn and kk, the matrix size and the required position.
  • Each of the next nn lines contains exactly nn integers ai,1,ai,2,…,ai,na_{i,1},a_{i,2},\ldots,a_{i,n}, in left-to-right order for row ii.

Output

  • Print one integer: the kk-th smallest matrix entry when repetitions are counted.

Subtasks

  • Subtask 1 (20 points): 1≤n≤101\le n\le10; 1≤k≤n21\le k\le n^2; −109≤ai,j≤109-10^9\le a_{i,j}\le10^9 for all 1≤i,j≤n1\le i,j\le n; all rows and columns are non-decreasing.
  • Subtask 2 (30 points): 1≤n≤601\le n\le60; 1≤k≤n21\le k\le n^2; −109≤ai,j≤109-10^9\le a_{i,j}\le10^9 for all 1≤i,j≤n1\le i,j\le n; all rows and columns are non-decreasing.
  • Subtask 3 (50 points): 1≤n≤3001\le n\le300; 1≤k≤n21\le k\le n^2; −109≤ai,j≤109-10^9\le a_{i,j}\le10^9 for all 1≤i,j≤n1\le i,j\le n; all rows and columns are non-decreasing.

Examples

Example 1

Input

3 8
1 5 9
10 11 13
12 13 15

Output

13

Explanation

Here n=3n=3 and k=8k=8. Sorting the nine entries gives 1,5,9,10,11,12,13,13,151,5,9,10,11,12,13,13,15. Both occurrences of 1313 must be counted; they occupy positions 77 and 88. The eighth entry is therefore 13.

Example 2

Input

1 1
-5

Output

-5

Explanation

There is only one matrix entry, −5-5, which is the first and only element of the sorted sequence. Hence the answer is -5.