Problem:


Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

1 \leq N, Q \leq 2 \times 10^5

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.



Sample input:
4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8


Sample output:
2
2
10
-1
13
-1

Submission status: Wrong Answer

Solution code:
# ABC128 E
from bisect import bisect_right as br
from bisect import bisect_left as bl

N,Q=map(int,input().split())
closed=[]
for _ in [0]*N:
    closed.append(tuple(map(int,input().split())))
closed.sort(key=lambda x:x[2])
    
D=[-int(input()) for _ in [0]*Q][::-1]

walk=[-1]*Q
for s,t,x in closed:
    ind=bl(D,x-(t-0.5))
    loop=br(D,x-(s-0.5))-ind
    for i in range(loop):
        if walk[ind+i]!=-1:
            break
        else:
            walk[ind+i]=x
print(*walk[::-1],sep='\n')

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18 if not DBG else 99999
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)


# # # # class Segtree # # # #

#      0
#   1     2
# 3   4  5  6
#       :
# leaf i - n-1+i
# parent   - (i-1)//2
# children - 2*i+1, 2*i+2

class Segtree:
    # modify UNIT and oper depending on the reduce operation

    #UNIT = 0  # sum/or:0 and:fff..f min:BIG max:-BIG gcd:0 lcm:1 ..

    #@classmethod
    #def oper(c,x,y):
    #    return x|y  # sum:+ or/and/min/max/gcd/lcm:(same)

    # call like this: sgt = Segtree(n, 0, lambda x,y: max(x,y))

    def __init__(s,l,unit,oper):
        s.unit = unit
        s.oper = oper
        s.n = 1
        while s.n<l:
            s.n *= 2
        s.ary = [s.unit for i in range(2*s.n-1)]

    def get(s,i):
        return s.ary[i+s.n-1]

    def set(s,i,v):
        k = i+s.n-1
        s.ary[k] = v
        while k>0:
            k = (k-1)//2
            s.ary[k] = s.oper( \
                        s.ary[2*k+1], s.ary[2*k+2])

    def setary(s,a):
        for i,v in enumerate(a):
            s.ary[i+s.n-1] = v
        for k in range(s.n-2,-1,-1):
            s.ary[k] = s.oper( \
                        s.ary[2*k+1], s.ary[2*k+2])

    def query(s,x,y):
        l = x+s.n-1
        r = y+s.n-1
        res = s.unit
        while l<r:
            if not l%2:
                res = s.oper(res,s.ary[l])
                l += 1
            if not r%2:
                r -= 1
                res = s.oper(res,s.ary[r])
            l >>= 1
            r >>= 1
        return res


# # # # class Segtree end # # # #

n,q = inm()
xs = set([])
stx = []
for i in range(n):
    s,t,x = inm()
    xs.add(x)
    xs.add(s-x)
    xs.add(t-x)
    stx.append((s-x,t-x,x))
stx.sort()

di = []
ans = [-1]*q
for i in range(q):
    d = inn()
    xs.add(d)
    di.append(d)

x2i = {}
i2x = list(xs)
m = len(xs)
i2x.sort()
for i,x in enumerate(i2x):
    x2i[x] = i

stx2 = []
for i in range(n):
    s,t,x = stx[i]
    stx2.append((x2i[s],x2i[t],x2i[x]))
d2 = [x2i[d] for d in di]

sgt = Segtree(m,BIG,lambda x,y: min(x,y))
top = 0
for j in range(q):
    d = d2[j]
    while top<n:
        s,t,x = stx2[top]
        if s>d:
            break
        if x<sgt.get(t-1):
            sgt.set(t-1,x)
        top += 1
    x = sgt.query(d,m)
    if x==BIG:
        print(-1)
    else:
        print(i2x[x])

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True  and False
BIG = 10**18 if not DBG else 9999
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)


# # # # class Segtree # # # #

#      0
#   1     2
# 3   4  5  6
#       :
# leaf i - n-1+i
# parent   - (i-1)//2
# children - 2*i+1, 2*i+2

class Segtree:
    # modify UNIT and oper depending on the reduce operation

    #UNIT = 0  # sum/or:0 and:fff..f min:BIG max:-BIG gcd:0 lcm:1 ..

    #@classmethod
    #def oper(c,x,y):
    #    return x|y  # sum:+ or/and/min/max/gcd/lcm:(same)

    # call like this: sgt = Segtree(n, 0, lambda x,y: max(x,y))

    def __init__(s,l,unit,oper):
        s.unit = unit
        s.oper = oper
        s.n = 1
        while s.n<l:
            s.n *= 2
        s.ary = [s.unit for i in range(2*s.n-1)]

    def get(s,i):
        return s.ary[i+s.n-1]

    def set(s,i,v):
        k = i+s.n-1
        s.ary[k] = v
        while k>0:
            k = (k-1)//2
            s.ary[k] = s.oper( \
                        s.ary[2*k+1], s.ary[2*k+2])

    def setary(s,a):
        for i,v in enumerate(a):
            s.ary[i+s.n-1] = v
        for k in range(s.n-2,-1,-1):
            s.ary[k] = s.oper( \
                        s.ary[2*k+1], s.ary[2*k+2])

    def query(s,x,y):
        l = x+s.n-1
        r = y+s.n-1
        res = s.unit
        while l<r:
            if not l%2:
                res = s.oper(res,s.ary[l])
                l += 1
            if not r%2:
                r -= 1
                res = s.oper(res,s.ary[r])
            l >>= 1
            r >>= 1
        return res


# # # # class Segtree end # # # #

n,q = inm()
xs = set([])
stx = []
for i in range(n):
    s,t,x = inm()
    xs.add(x)
    xs.add(s-x)
    xs.add(t-x)
    stx.append((s-x,t-x,x))
stx.sort()

di = []
ans = [-1]*q
for i in range(q):
    d = inn()
    xs.add(d)
    di.append(d)

x2i = {}
i2x = list(xs)
m = len(xs)
i2x.sort()
for i,x in enumerate(i2x):
    x2i[x] = i

stx2 = []
for i in range(n):
    s,t,x = stx[i]
    stx2.append((x2i[s],x2i[t],x2i[x]))
d2 = [x2i[d] for d in di]

ddprint(x2i)
ddprint(i2x)
ddprint(stx2)
ddprint(d2)

sgt = Segtree(m,BIG,lambda x,y: min(x,y))
top = 0
t2x = {}
for j in range(q):
    if DBG:
        #for i in range(m):
        #    printn(f"{sgt.get(i)} ")
        print('')
    d = d2[j]
    #ddprint(f"{d=}")
    while top<n:
        s,t,x = stx2[top]
        if s>d:
            break
        sgt.set(x,t)
        if t not in t2x or t2x[t]>x:
            t2x[t] = x
        top += 1
    while True:
        t = sgt.query(0,m)
        if t>d:
            break
        else:
            sgt.set(t2x[t],BIG)
    print(-1 if t==BIG else i2x[t2x[t]])

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N, Q = LI()
    sections = []
    D = []

    for _ in range(N):
        s, t, x = LI()
        s -= x
        t -= x
        sections.append((s, t, x))

    for _ in range(Q):
        D.append(I())
    sections = sorted(sections, key=lambda x: x[-1])

    section_end_ix = collections.defaultdict(list)

    filled = [-1] * Q
    for sec in sections:
        l = bisect.bisect_left(D, sec[0])
        r = bisect.bisect_left(D, sec[1])
        x = sec[2]
        # 調整 [0, 2, 5, 8, 9]、区間[1, 5]のとき、l = 1, r = 3になる。r = 2にする。
        # 調整 [0, 2, 5, 8, 9]、区間[2, 4]のとき、l = 1, r = 2になる。r = 1にする。
        r -= 1
        if r < 0:
            continue
        section_end_ix[x].append(r)
        ix = l
        while ix <= r:
            val_X = filled[ix] # 進める距離
            # 既に埋まってたら終点までスキップ
            if val_X > -1:
                _i = bisect.bisect_left(section_end_ix[val_X], ix) # section_end_ix[val_X]: 進める距離の終点のindexがのった配列
                # ix = 4、section_end_ix[val_X] = [2, 4, 7]のとき、2がかえる。

                if _i >= len(section_end_ix[val_X]):
                    # かぶってないのでよい
                    pass
                else:
                    # 終点までスキップ
                    ix = section_end_ix[val_X][_i]
            # うまってなかったら埋める
            else:
                filled[ix] = x
            ix += 1

    for x in filled:
        print(x)
main()

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N, Q = LI()
    sections = []
    D = []

    for _ in range(N):
        s, t, x = LI()
        s -= x
        t -= x
        sections.append((s, t, x))

    for _ in range(Q):
        D.append(I())
    sections = sorted(sections, key=lambda x: x[-1])

    section_end_ix = collections.defaultdict(list)

    filled = [-1] * Q
    for sec in sections:
        l = bisect.bisect_left(D, sec[0])
        r = bisect.bisect_left(D, sec[1])
        x = sec[2]
        # 調整 [0, 2, 5, 8, 9]、区間[1, 5]のとき、l = 1, r = 3になる。r = 2にする。
        r -= 1
        if r < 0:
            continue
        section_end_ix[x].append(r)
        ix = l
        while ix <= r:
            val_X = filled[ix] # 進める距離
            # 既に埋まってたら終点までスキップ
            if val_X > -1:
                _i = bisect.bisect_right(section_end_ix[val_X], ix) # section_end_ix[val_X]: 進める距離の終点のindexがのった配列
                # ix = 4、section_end_ix[val_X] = [2, 4, 7]のとき、2がかえる。

                if _i >= len(section_end_ix[val_X]):
                    # かぶってないのでよい
                    pass
                else:
                    # 終点までスキップ
                    ix = section_end_ix[val_X][_i]
            # うまってなかったら埋める
            else:
                filled[ix] = x
            ix += 1

    for x in filled:
        print(x)
main()

Submission status: Wrong Answer

Solution code:
import heapq
n, q = map(int, input().split())
event = []
for _ in range(n):
    s, t, x = map(int, input().split())
    event.append((s-x, 1, x))
    event.append((t-x, -1, x))

event.sort()
heap = []
xs = set([])

d = [int(input()) for _ in range(q)]
ans = [-1] * q
index = 0
for t, query, x in event:
    if d[index] < t:
        if not xs:
            pass
        else:
            while heap:
                tmp = heapq.heappop(heap)
                if tmp in xs:
                    heapq.heappush(heap, tmp)
                    ans[index] = tmp
                    break
        index += 1
        if index == q:
            break

    if query == 1:
        xs.add(x)
        heapq.heappush(heap, x)
    else:
        xs.remove(x)


while index < q:
    while heap:
        tmp = heapq.heappop(heap)
        if tmp in xs:
            heapq.heappush(heap, tmp)
            ans[index] = tmp
            break
    index += 1

print("\n".join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353

N, Q = map(int, input().split())

events = []
Xheap = []
heapq.heapify(Xheap)

for i in range(N):
    S, T, X = map(int, input().split())
    events.append([S-X-0.5, 1, X])
    events.append([T-X-0.5, -1, X])

events = sorted(events)

D = []
for i in range(Q):
    D.append(int(input()))

# print(events)
# print(D)

i = 0
for e in events:
    t = e[0]
    while D[i] <= t:
        if len(Xheap) == 0:
            print(-1)
        else:
            print(Xheap[0])
        i += 1
        if i == Q:
            sys.exit()

    if e[1] == 1:
        heapq.heappush(Xheap, e[2])
    else:
        Xheap.remove(e[2])

for j in range(i,Q):
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
from bisect import bisect_left

N, Q = [int(x) for x in input().split()]
data = []
for i in range(N):
    S, T, X = [int(x) for x in input().split()]
    data.append([X, S, T])
data.sort()
D = [int(input()) for _ in range(Q)]

ans = [-1]*Q
for X, S, T in data:
    l = bisect_left(D, S - X)
    r = bisect_left(D, T - X)
    for i in range(l, r):
        while l < r:
            if ans[i] == -1:
                ans[i] = X
                l += 1
            else:
                l += 1

for i in range(Q):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline

def main():
	N, Q = map(int, input().split())
	A = np.array([list(map(int, input().split())) for i in range(N)], dtype = np.int32)
	A = A[np.argsort(A[:, 2])]
	D = np.array([int(input()) for i in range(Q)], dtype = np.int32)
	ans = np.full(Q, -1)
	
	for i in range(N):
		S, T, X = A[i]
		l = np.searchsorted(D, S - X)
		r = np.searchsorted(D, T - X)
		print(l, r)
		ans[np.where(ans[l: r] == -1) + l] = X
	for i in range(Q):
		print(ans[i])


if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left
import sys
input = sys.stdin.readline

def main():
	N, Q = map(int, input().split())
	A = [tuple(map(int, input().split())) for i in range(N)]
	A.sort(key = lambda x: (x[2], x[0]))
	D = [int(input()) for i in range(Q)]
	ans = [-1] * Q
	
	donecnt = 0
	donei = set()
	for i in range(N):
		for j in range(bisect_left(D, A[i][0] - A[i][2]), bisect_left(D, A[i][1] - A[i][2])):
			if j in donei:
				continue
			ans[j] = A[i][2]
			donei.add(j)
			donecnt += 1
			if donecnt == Q:
				for k in range(Q):
					print(ans[k])
					exit()
	for k in range(Q):
		print(ans[k])
		
if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left
import sys
input = sys.stdin.readline

def main():
	N, Q = map(int, input().split())
	A = [tuple(map(int, input().split())) for i in range(N)]
	A.sort(key = lambda x: x[2])
	D = [int(input()) for i in range(Q)]
	ans = [-1] * Q
	
	donecnt = 0
	donei = set()
	for i in range(N):
		for j in range(bisect_left(D, A[i][0] - A[i][2]), bisect_left(D, A[i][1] - A[i][2])):
			if j in donei:
				continue
			ans[j] = A[i][2]
			donei.add(j)
			donecnt += 1
			if donecnt == Q:
				for k in range(Q):
					print(ans[k])
					exit()
	for k in range(Q):
		print(ans[k])
		
if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy


n, m = map(int,input().split())
k = []
for i in range(n):
    s, t, x = map(int,input().split())
    s -= x
    t -= x
    k.append([s, t, x])

q = []
for i in range(m):
    q.append(int(input()))
k = sorted(k, key=lambda x:(x[2], x[0], x[1]))

d = deque(k)
flg = True
for i in range(m):
    cq = q[i]
    if flg:
        s, t, x = d.popleft()
    flg = False
    while True:
        # print(cq, s, t, x)
        if cq < s:
            if d:
                flg = True
                dc = copy.deepcopy(d)
                s, t, x = d.popleft()
                continue
            else:
                print(-1)
                break
        elif s <= cq < t:
            print(x)
            break
        elif d:
            s, t, x = d.popleft()
        else:
            print(-1)
            if flg:
                d = dc
            break

Submission status: Wrong Answer

Solution code:
class AVLtree:
    """
    参考：http://www.nct9.ne.jp/m_hiroi/light/pyalgo12.html
    insert : 挿入
    erase : 削除
    lower_bound(x) : x <= v なる最小のv、なければ-float("inf")、最小値はlower(-float("inf"))
    upper_bound(x) : v < x なる最大のv、なければfloat("inf")、最大値はupper(float("inf"))
    print(avltree) : デバッグ用
    """
 
    def __init__(self):
        self.root = None

        
    def insert(self, x):
        if self.root is None:
            self.root = Node(x)
            return
        q = []
        node = self.root
        while True:
            if node.val == x:
                return
            elif x < node.val:
                q.append((node, 0))
                if node.left is None:
                    node.left = Node(x)
                    break
                node = node.left
            else:
                q.append((node, 1))
                if node.right is None:
                    node.right = Node(x)
                    break
                node = node.right
                
        # バランス調整
        new_node = None
        while q:
            node, key = q.pop()
            if not key:
                node.bal += 1
            else:
                node.bal -= 1
            bal = node.bal
            if not bal:
                return
            if bal == 2:
                if node.left.bal == -1:
                    node.left = node.left._rotateL()
                    new_node = node._rotateR()
                    new_node._update_bal()
                else:
                    new_node = node._rotateR()
                    new_node.bal = 0
                    node.bal = 0
                break
            elif bal == -2:
                if node.right.bal == 1:
                    node.right = node.right._rotateR()
                    new_node = node._rotateL()
                    new_node._update_bal()
                else:
                    new_node = node._rotateL()
                    new_node.bal = 0
                    node.bal = 0
                break
        if q:
            node, key = q.pop()
            if not key:
                node.left = new_node
            else:
                node.right = new_node
        elif new_node is not None:
            self.root = new_node

            
    def erase(self, x):
        if self.root is None:
            return
        q = []
        node = self.root
        while node is not None:
            if node.val == x:
                break
            if x < node.val:
                q.append((node, 0))
                node = node.left
            else:
                q.append((node, 1))
                node = node.right
        else:
            return
        if node.left is not None and node.right is not None:
            q.append((node, 1))
            min_node = node.right
            while min_node.left is not None:
                q.append((min_node, 0))
                min_node = min_node.left
            node = min_node
        if q:
            pre, key = q[-1]
        else:
            pre = None
        if node.left is None:
            cnode = node.right
        else:
            cnode = node.left
        if pre is None:
            self.root = cnode
            return
        if not key:
            pre.left = cnode
        else:
            pre.right = cnode
        
        # バランス調整
        while q:
            new_node = None
            node, key = q.pop()
            if not key:
                node.bal -= 1
            else:
                node.bal += 1
            bal = node.bal
            if bal == 2:
                if node.left.bal == -1:
                    node.left = node.left._rotateL()
                    new_node = node._rotateR()
                    new_node._update_bal()
                else:
                    new_node = node._rotateR()
                    if not new_node.bal:
                        new_node.bal = -1
                        node.bal = 1
                    else:
                        new_node.bal = 0
                        node.bal = 0
            elif bal == -2:
                if node.right.bal == 1:
                    node.right = node.right._rotateR()
                    new_node = node._rotateL()
                    new_node._update_bal()
                else:
                    new_node = node._rotateL()
                    if not new_node.bal:
                        new_node.bal = 1
                        node.bal = -1
                    else:
                        new_node.bal= 0
                        node.bal = 0
            elif bal:
                break
            if new_node is not None:
                if not q:
                    self.root = new_node
                    return
                node, key = q[-1]
                if not key:
                    node.left = new_node
                else:
                    node.right = new_node
                if new_node.bal:
                    break

                    
    def lower_bound(self, x):
        res = float("inf")
        node = self.root
        while node is not None:
            if x <= node.val:
                res = node.val
                node = node.left
            else:
                node = node.right
        return res
    
    
    def upper_bound(self, x):
        res = -float("inf")
        node = self.root
        while node is not None:
            if x <= node.val:
                node = node.left
            else:
                res = node.val
                node = node.right
        return res
    
    
    def __str__(self):
        if self.root is None:
            return "[]"
        buff = "["
        for x in self.root._dfs():
            buff += str(x)+", "
        buff = buff.rstrip(", ")
        buff += "]"
        return buff


class Node:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        self.bal = 0 #1:左1, -1:右1
    
    
    def _rotateR(self):
        nodeL = self.left
        self.left = nodeL.right
        nodeL.right = self
        return nodeL
    
    
    def _rotateL(self):
        nodeR = self.right
        self.right = nodeR.left
        nodeR.left = self
        return nodeR
    
    
    def _update_bal(self):
        if self.bal == 1:
            self.right.bal = -1
            self.left.bal = 0
        elif self.bal == -1:
            self.right.bal = 0
            self.left.bal = 1
        else:
            self.right.bal = 0
            self.left.bal = 0
        self.bal = 0
    
    
    def _dfs(self):
        if self is not None:
            if self.left is not None:
                for x in self.left._dfs():
                    yield x
            yield self.val
            if self.right is not None:
                for x in self.right._dfs():
                    yield x

n,q = map(int, input().split())
stx = [list(map(int, input().split())) for _ in range(n)]
e = [(s-x,x,i) for i,(s,_,x) in enumerate(stx)]+[(t-x,x,i) for i,(_,t,x) in enumerate(stx)]
d = [int(input()) for _ in range(q)]
e += [(di,float("inf"),i) for i,di in enumerate(d)]
e.sort(key = lambda x:x[0])
avl = AVLtree()
ans = []
f = [0]*n
for s,x,i in e:
  if x == float("inf"):
    m = avl.lower_bound((-float("inf"),0))
    ans.append(m[0] if m != float("inf") else -1)
  elif f[i]:
    avl.erase(f[i])
  else:
    avl.insert((x,i))
    f[i] = (x,i)
for i in ans:
  print(i)