using
System;
using
System.Collections.Generic;
namespace
MinInterval
{
class
Program
{
public
static
List<
int
> minInterval(List<List<
int
>> intervals, List<
int
> q)
{
List<List<
int
>> queries =
new
List<List<
int
>>();
for
(
int
i = 0; i < q.Count; i++)
queries.Add(
new
List<
int
> { q[i], i });
intervals.Sort();
queries.Sort();
PriorityQueue<List<
int
>> pq =
new
PriorityQueue<List<
int
>>();
List<
int
> result =
new
List<
int
>(queries.Count);
for
(
int
i = 0; i < result.Capacity; i++)
{
result[i] = -1;
}
int
i = 0;
for
(
int
j = 0; j < queries.Count; j++)
{
int
temp = queries[j][0];
while
(i < intervals.Count && intervals[i][0] <= temp)
{
pq.Push(
new
List<
int
> { -intervals[i][1] + intervals[i][0] - 1, intervals[i++][1] });
}
while
(pq.Count != 0 && temp > pq.Peek()[1])
{
pq.Pop();
}
if
(pq.Count != 0)
result[queries[j][1]] = -pq.Peek()[0];
}
return
result;
}
static
void
Main(
string
[] args)
{
List<List<
int
>> intervals =
new
List<List<
int
>> {
new
List<
int
> { 1, 4 },
new
List<
int
> { 2, 3 },
new
List<
int
> { 3, 6 },
new
List<
int
> { 9, 25 },
new
List<
int
> { 7, 15 },
new
List<
int
> { 4, 4 } };
List<
int
> Q =
new
List<
int
> { 7, 50, 2, 3, 4, 9 };
List<
int
> result = minInterval(intervals, Q);
foreach
(
int
res
in
result)
Console.Write(res +
" "
);
}
}
public
class
PriorityQueue<T>
{
private
readonly
List<T> heap;
private
readonly
Comparison<T> compare;
public
PriorityQueue() :
this
(Comparer<T>.Default) { }
public
PriorityQueue(IComparer<T> comparer) :
this
(comparer.Compare) { }
public
PriorityQueue(Comparison<T> comparison)
{
this
.heap =
new
List<T>();
this
.compare = comparison;
}
public
void
Push(T item)
{
this
.heap.Add(item);
int
i =
this
.heap.Count - 1;
while
(i > 0)
{
int
p = (i - 1) / 2;
if
(
this
.compare(
this
.heap[p], item) <= 0)
break
;
this
.heap[i] =
this
.heap[p];
i = p;
}
this
.heap[i] = item;
}
public
T Pop()
{
T ret =
this
.heap[0];
T item =
this
.heap[
this
.heap.Count - 1];
this
.heap.RemoveAt(
this
.heap.Count - 1);
if
(
this
.heap.Count == 0)
return
ret;
int
i = 0;
while
(i * 2 + 1 <
this
.heap.Count)
{
int
a = i * 2 + 1;
int
b = i * 2 + 2;
if
(b <
this
.heap.Count &&
this
.compare(
this
.heap[b],
this
.heap[a]) < 0)
a = b;
if
(
this
.compare(item,
this
.heap[a]) <= 0)
break
;
this
.heap[i] =
this
.heap[a];
i = a;
}
this
.heap[i] = item;
return
ret;
}
public
T Peek()
{
if
(
this
.heap.Count == 0)
throw
new
InvalidOperationException();
return
this
.heap[0];
}
public
int
Count {
get
{
return
this
.heap.Count; } }
}
}