using
System;
using
System.Collections.Generic;
public
class
Node : IComparable<Node>
{
public
int
Data {
get
;
private
set
; }
public
int
Row {
get
;
private
set
; }
public
int
NextCol {
get
;
private
set
; }
public
Node(
int
data,
int
row,
int
nextCol)
{
Data = data;
Row = row;
NextCol = nextCol;
}
public
int
CompareTo(Node other)
{
return
Data.CompareTo(other.Data);
}
}
public
class
Program
{
public
static
void
FindSmallestRange(List<List<
int
>> arr,
int
k,
int
n)
{
var
minHeap =
new
MinHeap<Node>();
int
maxValue = 0;
int
smallestRange =
int
.MaxValue;
int
start = -1;
int
end = -1;
for
(
int
i = 0; i < k; i++)
{
var
node =
new
Node(arr[i][0], i, 0);
minHeap.Add(node);
maxValue = Math.Max(maxValue, arr[i][0]);
}
while
(minHeap.Count > 0)
{
var
node = minHeap.ExtractMin();
int
minValue = node.Data;
if
(smallestRange > maxValue - minValue)
{
smallestRange = maxValue - minValue;
start = minValue;
end = maxValue;
}
int
row = node.Row;
int
nextCol = node.NextCol;
if
(nextCol + 1 < n)
{
var
nextNode =
new
Node(arr[row][nextCol + 1], row, nextCol + 1);
minHeap.Add(nextNode);
maxValue = Math.Max(maxValue, arr[row][nextCol + 1]);
}
else
{
break
;
}
}
Console.WriteLine($
"{start} {end}"
);
}
public
static
void
Main(
string
[] args)
{
List<List<
int
>> arr =
new
List<List<
int
>>()
{
new
List<
int
>(){1, 3, 5, 7, 9},
new
List<
int
>(){0, 2, 4, 6, 8},
new
List<
int
>(){2, 3, 5, 7, 11}
};
int
k = 3;
int
n = 5;
FindSmallestRange(arr, k, n);
}
}
public
class
MinHeap<T>
where
T : IComparable<T>
{
private
List<T> heap;
public
MinHeap()
{
heap =
new
List<T>();
}
public
int
Count {
get
{
return
heap.Count; } }
public
void
Add(T item)
{
heap.Add(item);
int
currentIndex = heap.Count - 1;
while
(currentIndex > 0)
{
int
parentIndex = (currentIndex - 1) / 2;
if
(heap[currentIndex].CompareTo(heap[parentIndex]) >= 0)
break
;
Swap(currentIndex, parentIndex);
currentIndex = parentIndex;
}
}
public
T ExtractMin()
{
int
lastIndex = heap.Count - 1;
T min = heap[0];
heap[0] = heap[lastIndex];
heap.RemoveAt(lastIndex);
Heapify(0);
return
min;
}
private
void
Heapify(
int
index)
{
int
left = index * 2 + 1;
int
right = index * 2 + 2;
int
smallest = index;
if
(left < heap.Count && heap[left].CompareTo(heap[smallest]) < 0)
smallest = left;
if
(right < heap.Count && heap[right].CompareTo(heap[smallest]) < 0)
smallest = right;
if
(smallest != index)
{
Swap(index, smallest);
Heapify(smallest);
}
}
private
void
Swap(
int
i,
int
j)
{
T temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
}