using
System;
using
System.Linq;
class
GFG
{
static
int
[] segmentTree;
public
static
int
getMid(
int
start,
int
end)
{
return
start + (end - start) / 2;
}
public
static
void
fillSegmentTree(
int
[][] arr)
{
Array.Sort(arr, (x, y) => x[0].CompareTo(y[0]));
int
n = arr.Length;
int
maxHeight = (
int
)Math.Ceiling(Math.Log(n) / Math.Log(2));
int
maxSize = 2 * (
int
)Math.Pow(2, maxHeight) - 1;
segmentTree =
new
int
[maxSize];
fillSegmentTreeUtil(segmentTree, arr, 0, n - 1, 0);
}
public
static
int
fillSegmentTreeUtil(
int
[] segmentTree,
int
[][] arr,
int
start,
int
end,
int
currNode)
{
if
(start == end)
{
segmentTree[currNode] = arr[start][1];
return
segmentTree[currNode];
}
int
mid = getMid(start, end);
segmentTree[currNode] = Math.Max(
fillSegmentTreeUtil(segmentTree, arr, start, mid, currNode * 2 + 1),
fillSegmentTreeUtil(segmentTree, arr, mid + 1, end, currNode * 2 + 2));
return
segmentTree[currNode];
}
public
static
int
findMaxRating(
int
[][] arr,
int
[] query)
{
int
n = arr.Length;
return
findMaxRatingUtil(segmentTree, arr, 0, n - 1, query[0], query[1], 0);
}
public
static
int
findMaxRatingUtil(
int
[] segmentTree,
int
[][] arr,
int
start,
int
end,
int
qStart,
int
qEnd,
int
currNode)
{
if
(qStart <= arr[start][0] && qEnd >= arr[end][0])
{
return
segmentTree[currNode];
}
if
(qStart > arr[end][0] || qEnd < arr[start][0])
{
return
-1;
}
int
mid = getMid(start, end);
return
Math.Max(
findMaxRatingUtil(segmentTree, arr, start, mid, qStart, qEnd, currNode * 2 + 1),
findMaxRatingUtil(segmentTree, arr, mid + 1, end, qStart, qEnd, currNode * 2 + 2));
}
public
static
void
Main(
string
[] args)
{
int
[][] arr =
new
int
[5][];
arr[0] =
new
int
[] { 1000, 300 };
arr[1] =
new
int
[] { 1100, 400 };
arr[2] =
new
int
[] { 1300, 200 };
arr[3] =
new
int
[] { 1700, 500 };
arr[4] =
new
int
[] { 2000, 600 };
fillSegmentTree(arr);
int
[][] queries =
new
int
[3][];
queries[0] =
new
int
[] { 1000, 1400 };
queries[1] =
new
int
[] { 1700, 1900 };
queries[2] =
new
int
[] { 0, 3000 };
foreach
(
int
[] query
in
queries)
{
Console.WriteLine(findMaxRating(arr, query));
}
}
}