using
System;
using
System.Collections.Generic;
public
class
Node {
public
int
Data {
get
;
set
; }
public
int
Row {
get
;
set
; }
public
int
Col {
get
;
set
; }
public
Node(
int
data,
int
row,
int
col) {
Data = data;
Row = row;
Col = col;
}
}
public
class
Solution {
public
int
Median(List<List<
int
>> matrix,
int
R,
int
C) {
var
minHeap =
new
PriorityQueue<Node>((a, b) =>
a.Data.CompareTo(b.Data));
int
count = 0, median = -1;
int
medianIndex = (R * C) / 2;
for
(
int
i = 0; i < R; i++) {
var
temp =
new
Node(matrix[i][0], i, 0);
minHeap.Enqueue(temp);
}
while
(count <= medianIndex) {
var
top = minHeap.Dequeue();
int
row = top.Row;
int
col = top.Col;
median = top.Data;
count++;
if
(col + 1 < C) {
col++;
var
temp =
new
Node(matrix[row][col], row, col);
minHeap.Enqueue(temp);
}
}
return
median;
}
}
public
class
PriorityQueue<T> {
private
List<T> heap;
private
Comparison<T> comparison;
public
PriorityQueue(Comparison<T> comparison) {
heap =
new
List<T>();
this
.comparison = comparison;
}
public
int
Count {
get
{
return
heap.Count; }
}
public
void
Enqueue(T item) {
heap.Add(item);
int
i = heap.Count - 1;
while
(i > 0) {
int
parent = (i - 1) / 2;
if
(comparison(heap[parent], item) <= 0) {
break
;
}
heap[i] = heap[parent];
i = parent;
}
heap[i] = item;
}
public
T Dequeue() {
T item = heap[0];
int
lastIndex = heap.Count - 1;
heap[0] = heap[lastIndex];
heap.RemoveAt(lastIndex);
lastIndex--;
int
i = 0;
while
(
true
) {
int
leftChild = 2 * i + 1;
int
rightChild = 2 * i + 2;
if
(leftChild > lastIndex) {
break
;
}
int
minChild = leftChild;
if
(rightChild <= lastIndex &&
comparison(heap[rightChild], heap[leftChild]) < 0)
{
minChild = rightChild;
}
if
(comparison(heap[i], heap[minChild]) <= 0) {
break
;
}
T temp = heap[i];
heap[i] = heap[minChild];
heap[minChild] = temp;
i = minChild;
}
return
item;
}
public
T Peek() {
return
heap[0];
}
}
public
class
GFG {
public
static
void
Main() {
int
R = 3;
int
C = 3;
var
matrix =
new
List<List<
int
>> {
new
List<
int
> {1, 3, 5},
new
List<
int
> {2, 6, 9},
new
List<
int
> {3, 6, 9}
};
var
obj =
new
Solution();
Console.WriteLine(obj.Median(matrix, R, C));
}
}