using
System;
using
System.Collections;
using
System.Collections.Generic;
public
class
GFG {
static
int
[] seg_tree;
static
int
combine(
int
a,
int
b)
{
return
Math.Min(a, b);
}
static
void
build(
int
[] arr,
int
node,
int
tl,
int
tr)
{
if
(tl == tr) {
seg_tree[node] = arr[tl];
}
else
{
int
tm = (tr - tl) / 2 + tl;
build(arr, 2 * node, tl, tm);
build(arr, 2 * node + 1, tm + 1, tr);
seg_tree[node] = combine(
seg_tree[2 * node], seg_tree[2 * node + 1]);
}
}
static
void
update(
int
node,
int
tl,
int
tr,
int
pos,
int
new_val)
{
if
(tl == tr) {
seg_tree[node] = new_val;
}
else
{
int
tm = (tr - tl) / 2 + tl;
if
(pos <= tm) {
update(2 * node, tl, tm, pos, new_val);
}
else
{
update(2 * node + 1, tm + 1, tr, pos,
new_val);
}
seg_tree[node] = combine(
seg_tree[2 * node], seg_tree[2 * node + 1]);
}
}
static
int
query(
int
node,
int
tl,
int
tr,
int
l,
int
r)
{
if
(l > r) {
return
Int32.MaxValue;
}
if
(l == tl && r == tr) {
return
seg_tree[node];
}
int
tm = (tr - tl) / 2 + tl;
int
q1
= query(2 * node, tl, tm, l, Math.Min(r, tm));
int
q2 = query(2 * node + 1, tm + 1, tr,
Math.Max(l, tm + 1), r);
return
combine(q1, q2);
}
static
void
printNSE(
int
[] original,
int
n)
{
int
[] sorted =
new
int
[n];
Dictionary<
int
,
int
> encode
=
new
Dictionary<
int
,
int
>();
for
(
int
i = 0; i < n; i++) {
sorted[i] = original[i];
}
Array.Sort(sorted);
int
ctr = 0;
for
(
int
i = 0; i < n; i++) {
if
(!encode.ContainsKey(sorted[i])) {
encode.Add(sorted[i], ctr++);
}
}
int
[] compressed =
new
int
[n];
for
(
int
i = 0; i < n; i++) {
compressed[i] = encode[original[i]];
}
int
[] aux =
new
int
[ctr];
for
(
int
i = 0; i < ctr; i++) {
aux[i] = Int32.MaxValue;
}
seg_tree =
new
int
[4 * ctr];
build(aux, 1, 0, ctr - 1);
int
[] ans =
new
int
[n];
for
(
int
i = n - 1; i >= 0; i--) {
ans[i] = query(1, 0, ctr - 1, 0,
compressed[i] - 1);
update(1, 0, ctr - 1, compressed[i], i);
}
for
(
int
i = 0; i < n; i++) {
Console.Write(original[i] +
" ---> "
);
if
(ans[i] == Int32.MaxValue) {
Console.WriteLine(-1);
}
else
{
Console.WriteLine(original[ans[i]]);
}
}
}
static
public
void
Main()
{
int
[] arr = { 11, 13, 21, 3 };
printNSE(arr, 4);
}
}