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: Accepted

Solution code:
import sys
input = sys.stdin.readline


n, q = map(int, input().split())
events = []
for _ in range(n):
    start, end, pos = map(int, input().split())
    events.append([start - pos, 1, pos])
    events.append([end - pos, 0, pos])

events.sort()

departures = [int(input()) for _ in range(q)]

idx = 0
mini = 10**10
mini_check = False
candidates = set()
time, is_under_construction, pos = events[idx]
for departure in departures:
    while time <= departure:
        if is_under_construction:
            candidates.add(pos)
            if pos < mini:
                mini = pos
                mini_check = True
        else:
            candidates.remove(pos)
            if pos == mini:
                mini_check = False
        idx += 1
        if idx == 2 * n:
            time = float('INF')
            break
        time, is_under_construction, pos = events[idx]

    if not candidates:
        print(-1)
    else:
        if not mini_check:
            mini = min(candidates)
            mini_check = True
        print(mini)

Submission status: Accepted

Solution code:

n,q=[int(j) for j in input().split()]
l=[]
for i in range(n):
    s,t,x=[int(j) for j in input().split()]
    l.append((s-x,1,x))
    l.append((t-x,0,x))

for i in range(q):
    d=int(input())
    l.append((d,2,i))

l.sort()

ans=[-1]*q
ll=set()
m=10**18
p=False
for i,j,x in l:
    if j==1:
        ll.add(x)
        if m>x:
            m=x
            p=True
    elif j==0:
        ll.remove(x)
        if x==m:
            p=False
    else:
        if not p:
            if ll:
                p=True
                m=min(ll)
            else:
                m=-1
        ans[x]=m
print('\n'.join(map(str,ans)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline

N,Q = map(int, input().split())
List = []
dic = {}
for _ in range(N):
    s, t, x = map(int, input().split())
    List.append((s-0.5-x, 1, x))
    List.append((t-0.5-x, -1, x))
    dic[x] = False

import heapq
    
List.sort()

h = []
j = 0
for _ in range(Q):
    D = int(input())
    while j < 2*N and List[j][0] < D:
        if List[j][1] == 1:
            heapq.heappush(h, List[j][2])
            dic[List[j][2]] = True
        else:
            dic[List[j][2]] = False
        j += 1
    while h:
        ans = h[0]
        if dic[ans]:
            print(ans)
            break
        else:
            heapq.heappop(h)
    if not h:
        print(-1)

Submission status: Accepted

Solution code:
# ref https://www.owlog.org/abc128/

import sys
sys.setrecursionlimit(10 ** 7)
from bisect import bisect_left

def main():
    input = sys.stdin.readline
    N, Q = map(int, input().split())

    # 通行止めの地点 (X,S,T)
    closure = []
    for _ in range(N):
        start, end, pos = map(int, input().split())
        closure.append((pos, start, end))

    # 座標の昇順でソート
    closure.sort()

    D = [int(input()) for _ in range(Q)]

    # 各人の止まる地点
    ans = [-1] * Q
    # その人が既に止まっているか
    skip = [-1] * Q

    # 各通行止めの地点で止まる人を探索
    # Dが範囲[S-X,T-X)にあるときに止まる
    for pos, start, end in closure:
        # 一番左の人のインデックス
        left = bisect_left(D, start - pos)
        # 一番右の人のインデックス
        right = bisect_left(D, end - pos)

        while left < right:
            if skip[left] == -1:
                # 停止座標を記録
                ans[left] = pos
                # 右端の人のインデックスを記録
                skip[left] = right
                left += 1
            else:
                # [left,skip[left])にいる人は既に止まっている
                left = skip[left]

    return ans


if __name__ == '__main__':
    print(*main(), sep='\n')

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left
    from bisect import bisect_right
    from sys import stdin
    input=stdin.readline

    n,q=map(int,input().split())
    stx=[list(map(int,input().split())) for _ in [0]*n]
    d=[int(input()) for _ in [0]*q]
    stx=[[s-x,t-x-1,x] for s,t,x in stx]
    stx=[[bisect_left(d,s),bisect_right(d,t),x] for s,t,x in stx]

    #セグ木の要素数（num）および深さ（depth）を計算
    basesize=q
    num,depth=1,1
    while num<basesize:
        num*=2
        depth+=1
    num-=1
    #セグ木を構築
    treesize=num+basesize
    tree=[10**9+1]*treesize
    
    #半開区間[lower,upper)について更新の準備をする関数
    def range_update_pre(lower,upper,new_value):
        q=[[0,1]]  #インデックス、階層
        while q:
            i,f=q.pop()
            #popしたインデックスと階層から、求める下限と上限を算出する
            #幅
            width=pow(2,depth-f)
            #下限と中央と上限
            kagen=(i-pow(2,f-1)+1)*width
            chuo=kagen+width//2
            jogen=kagen+width
            k=2*i+1
            if lower<=kagen and jogen<=upper:
                tree[i]=min(new_value,tree[i])
                continue
            if k<treesize:
                if lower<=kagen and chuo<=upper:tree[k]=min(new_value,tree[k])
                elif lower<=chuo:q.append([k,f+1])
            if k+1<treesize:
                if lower<=chuo and jogen<=upper:tree[k+1]=min(new_value,tree[k+1])
                elif chuo<=upper:q.append([k+1,f+1])

    for s,t,x in stx:
        if s<t:
            range_update_pre(s,t,x)

    for i in range(1,treesize):
        tree[i]=min(tree[i],tree[(i-1)//2])

    ans=[i for i in tree[treesize-basesize:]]
    for i in ans:
        if i==10**9+1:
            print(-1)
        else:
            print(i)
main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc128/submissions/8312583
# 写経

def solve():
    from heapq import heappush, heappop
    from collections import defaultdict
    from operator import itemgetter
    import sys

    input = sys.stdin.readline

    inf = 1 << 31

    n, q = map(int, input().split())

    S = [0] * n
    T = [0] * n
    X = [0] * n
    for i in range(n):
        S[i], T[i], X[i] = map(int, input().split())

    e = [(t - x, 0, x) for t, x in zip(T, X)]
    e.extend([(s - x, 1, x) for s, x in zip(S, X)])
    e.extend([(int(input()), 2, idx) for idx in range(q)])
    # e = [*((t - x, 0, x) for t, x in zip(T, X)),
    #      *((s - x, 1, x) for s, x in zip(S, X)),
    #      *((int(input()), 2, idx) for idx in range(q))
    #      ]
    e.sort(key=itemgetter(0))
    # 安定ソートなので、0,1,2順になる（はず

    cnt = defaultdict(int)
    cnt[inf] = 1
    h = [inf]
    ret = [-1] * q
    for time, type, x in e:
        if type == 0:
            cnt[x] -= 1
        elif type == 1:
            heappush(h, x)
            cnt[x] += 1
        else:
            while not (cnt[h[0]]):
                heappop(h)
            curr = h[0]
            if curr != inf:
                ret[x] = curr

    print(*ret, sep='\n')


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC128 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,q = LI()
stx = [LI() for _ in range(n)]
d = [I() for _ in range(q)]
stx.sort(key = lambda x:(x[2],x[0]))
ans = [-1]*q
skip = [-1]*q
for s,t,x in stx:
    l = bl(d,s-x)
    r = bl(d,t-x)
    while l < r:
        if ans[l] < 0:
            skip[l] = r
            ans[l] = x
            l += 1
        else:
            l = skip[l]
print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush

N, Q = map(int, input().split())
INF = float('inf')

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

for _ in range(Q):
    events.append((int(input()), 2, 0))

events.sort()

cnt = defaultdict(int)
cnt[INF] += 1
que = [INF]

for t, flag, x in events:
    if flag == 0:
        if cnt[x] == 0:
            heappush(que, x)
        cnt[x] += 1
    elif flag == 1:
        cnt[x] -= 1
    else:
        while cnt[que[0]] == 0:
            heappop(que)
        print(que[0] if que[0] != INF else -1)

Submission status: Accepted

Solution code:
class SegmentTree :
    def __init__(self, n) :
        self.n = n
        self.N0 = 1 << n.bit_length()
        self.data = [10**15] * (self.N0*2)
 
    def update(self, l, r, val) :
        l += self.N0
        r += self.N0
        while l < r:
            if l & 1 :
                self.data[l] = min(self.data[l], val)
                l += 1
            if r & 1:
                self.data[r-1] = min(self.data[r-1], val)
                r -= 1
            l //= 2
            r //= 2
 
    def query(self, i) :
        i += len(self.data) // 2
        ret = self.data[i]
        while i > 0 :
            i //= 2
            ret = min(ret, self.data[i])
        return ret if ret < 10**15 else -1
import bisect
import sys
input = sys.stdin.readline
N, Q = map(int, input().split())
roads = []
for _ in range(N):
    s, t, x = map(int, input().split())
    roads.append((x, s, t))
compress_list = []
query = []
for _ in range(Q):
    d = int(input())
    compress_list.append(d)
S = SegmentTree(Q)
for x, s, t in roads:
    l = bisect.bisect_left(compress_list, s-x)
    r = bisect.bisect_left(compress_list, t-x)
    S.update(l, r, x)
for i in range(Q):
    print(S.query(i))

Submission status: Accepted

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

def main():
    n,q=map(int,input().split())
    xst=[]
    for i in range(n):
        s,t,x=map(int,input().split())
        xst.append([x,s-x,t-x])
    xst.sort()
    d=[None]*q
    for i in range(q):
        d[i]=int(input())
    ans=[-1]*q
    skip=[-1]*q
    for u in xst:
        x ,left ,right = u
        a=bisect_left(d,left)
        b=bisect_left(d,right)
        while a < b:
            if skip[a] == -1:
                ans[a]=x
                skip[a]=b
                a+=1
            else:
                a=skip[a]
    for u in ans:
        print(u)

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a, p = LI()
    print((a*3+p)//2)
    return

#B
def B():
    n = II()
    sp = []
    for i in range(n):
        sp.append(input().split())
    another = [(s[0], -1 * int(s[1]),num) for num,s in enumerate(sp)]
    another.sort()
    for s,p,q in another:
        print(q+1)

    return

#C
def C():
    n, m = LI()
    ks = LIR_(m)
    p = LI()
    patern = itertools.product(range(2), repeat=n)
    ans = 0
    for on in patern:
        ki = [0 for i in range(m)]
        for num, oni in enumerate(on):
            if oni:
                for i,ksi in enumerate(ks):
                    ksi = ksi[1::]
                    if num in ksi:
                        ki[i] ^= 1
        for num, pi in enumerate(p):
            if pi != ki[num]:
                break
        else:
            ans += 1
    print(ans)

            
    return

#D
def D():
    N, K = LI()#random.randint(1,50),random.randint(1,100)
    v = LI()#[random.randint(-10 ** 2, 10 ** 2) for i in range(N)]
    ans = 0
    for a in range(min(N, K) + 1):
        for b in range(min(N, K) + 1):
            if a + b > min(K,N):
                break
            if a == b == 0:
                continue
            deletes = K - a - b
            left = v[:a]
            right = v[:-b-1:-1]
            x = left + right
            x.sort()
            tmp = sum(x)
            for delete in range(min(deletes, len(x))):
                if x[delete] >= 0:
                    break
                tmp -= x[delete]
            ans = max(ans,tmp)
    
    print(ans)
                

    return


#E
def E():  
    N,q = LI()
    STX = LIR(N)
    D = IR(q)
    LV = (q - 1).bit_length()
    N0 = 1 << LV

    data = [inf] * (N0 << 1)
    INF = inf

    def update(l, r, x):
    
        #  区間[l, r)のdataの値を更新
        L = N0 + l; R = N0 + r
        while L < R:
            if R & 1:
                R -= 1
                data[R-1] = min(data[R-1], x)
            if L & 1:
                data[L-1] = min(data[L-1], x)
                L += 1
            L >>= 1; R >>= 1

    def query(x):
        L = N0 + x - 1
        #  xの最小値を求める
        s = INF
        while L >= 0:
            s = min(s, data[L])
            L = (L - 1) >> 1
        return s

    for s, t, x in STX:
        XS = max(-1, s - x)
        XT = max(-1, t - x)
        XS_index = bisect_left(D, XS)
        XT_index = bisect_left(D, XT)
        update(XS_index, XT_index, x)

    for i in range(q):
        a = query(i)
        print(a if a != inf else -1)
#F
def F():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop
n,q=map(int,input().split())
a=sorted(((s-x, t-x, x) for _ in range(n) for s, t, x in (map(int, sys.stdin.readline().split()),)), reverse=True)
heap=[]
ans=[]
z=list(map(int,sys.stdin))
for d in z:
  while a and a[-1][0]<=d:
    e=a.pop()
    heappush(heap,(e[2],e[1]))
  while heap and heap[0][1]<=d:
    heappop(heap)
  if heap:
    ans.append(heap[0][0])
  else:
    ans.append(-1)

print(*ans, sep='\n')

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop
n,q=map(int,input().split())
a=sorted(((s-x, t-x, x) for _ in range(n) for s, t, x in (map(int, sys.stdin.readline().split()),)), reverse=True)
heap=[]
ans=[]
for i in range(q):
  d=int(input())
  while a and a[-1][0]<=d:
    e=a.pop()
    heappush(heap,(e[2],e[1]))
  while heap and heap[0][1]<=d:
    heappop(heap)
  if heap:
    ans.append(heap[0][0])
  else:
    ans.append(-1)

print(*ans, sep='\n')

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,q=map(int,input().split())
    S,T,X=[0]*n,[0]*n,[0]*n
    for i in range(n):
        S[i],T[i],X[i]=map(int,input().split())
    D=[int(input()) for _ in range(q)]

    E=[]
    E+=[(s-x,1,x) for s,x in zip(S,X)]
    E+=[(t-x,2,x) for t,x in zip(T,X)]
    E+=[(d,3,i) for i,d in enumerate(D)]
    E.sort()
    from collections import defaultdict
    cnt=defaultdict(int)
    cnt[INF]=1

    from heapq import heappop,heappush
    Q=[INF]
    ans=[-1]*q
    for a,b,c in E:
        if(b==1):
            heappush(Q,c)
            cnt[c]+=1
        elif(b==2): # 本来はここでqからcを削除したいが、できないためb==3で処理する
            cnt[c]-=1
        else:
            while(cnt[Q[0]]==0): # 本来削除されるべき通行止めをここで消す
                heappop(Q)
            x=Q[0]
            if(x!=INF): ans[c]=x
    print(*ans,sep="\n")
resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,q=map(int,input().split())
    S,T,X=[0]*n,[0]*n,[0]*n
    D=[0]*q
    for i in range(n):
        S[i],T[i],X[i]=map(int,input().split())
    for j in range(q):
        D[j]=int(input())

    E=[]
    E+=[(s-x,1,x) for s,x in zip(S,X)]
    E+=[(t-x,2,x) for t,x in zip(T,X)]
    E+=[(d,3,i) for i,d in enumerate(D)]
    E.sort()
    from collections import defaultdict
    cnt=defaultdict(int)
    cnt[INF]=1

    from heapq import heappop,heappush
    Q=[INF]
    ans=[-1]*q
    for a,b,c in E:
        if(b==1):
            heappush(Q,c)
            cnt[c]+=1
        elif(b==2): # 本来はここでqからcを削除したいが、できないためb==3で処理する
            cnt[c]-=1
        else:
            while(cnt[Q[0]]==0): # 本来削除されるべき通行止めをここで消す
                heappop(Q)
            x=Q[0]
            if(x!=INF): ans[c]=x
    print(*ans,sep="\n")
resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.buffer.readline().rstrip()
def resolve():
    n,q=map(int,input().split())
    S,T,X=[0]*n,[0]*n,[0]*n
    D=[0]*q
    for i in range(n):
        S[i],T[i],X[i]=map(int,input().split())
    for j in range(q):
        D[j]=int(input())

    E=[]
    E+=[(s-x,1,x) for s,x in zip(S,X)]
    E+=[(t-x,2,x) for t,x in zip(T,X)]
    E+=[(d,3,i) for i,d in enumerate(D)]
    E.sort()
    from collections import defaultdict
    cnt=defaultdict(int)
    cnt[INF]=1

    from heapq import heappop,heappush
    Q=[INF]
    ans=[-1]*q
    for a,b,c in E:
        if(b==1):
            heappush(Q,c)
            cnt[c]+=1
        elif(b==2): # 本来はここでqからcを削除したいが、できないためb==3で処理する
            cnt[c]-=1
        else:
            while(cnt[Q[0]]==0): # 本来削除されるべき通行止めをここで消す
                heappop(Q)
            x=Q[0]
            if(x!=INF): ans[c]=x
    print(*ans,sep="\n")
resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,q=map(int,input().split())
    S,T,X=[0]*n,[0]*n,[0]*n
    D=[0]*q
    for i in range(n):
        S[i],T[i],X[i]=map(int,input().split())
    for j in range(q):
        D[j]=int(input())

    E=[]
    E+=[(s-x,1,x) for s,x in zip(S,X)]
    E+=[(t-x,2,x) for t,x in zip(T,X)]
    E+=[(d,3,i) for i,d in enumerate(D)]
    E.sort()
    cnt={x:0 for x in X}
    cnt[INF]=1

    from heapq import heappop,heappush
    Q=[INF]
    ans=[-1]*q
    for a,b,c in E:
        if(b==1):
            heappush(Q,c)
            cnt[c]+=1
        elif(b==2): # 本来はここでqからcを削除したいが、できないためb==3で処理する
            cnt[c]-=1
        else:
            while(cnt[Q[0]]==0): # 本来削除されるべき通行止めをここで消す
                heappop(Q)
            x=Q[0]
            if(x!=INF): ans[c]=x
    print(*ans,sep="\n")
resolve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect_left
inf = float('inf')

# 区間更新　一点取得　1-indexed
class SegmentTree:
    def __init__(self, N):
        tmp = 1
        while tmp < N:
            tmp <<= 1
        # self.N : 完全二分木の葉の数(N以上の最小の2べき)
        self.N = tmp
        # 2*self.N - 1 : 完全二分木のノード数
        # 1-indexedで管理するので余分に１つ設ける
        self.Data = [inf for _ in range(2*self.N)]
    
    # [l, r) (0-indexed)
    def update(self, l, r, x):
        # インデックスを補正
        L = l + self.N
        R = r + self.N
        while L < R:
            # 右側なら右側を更新 右上に行く
            # 左側なら更新しない　上に行く
            if L & 1:
                self.Data[L] = min([self.Data[L], x])
                L += 1
            # 右側なら左側を更新　上に行く
            # 左側なら更新しない 上に行く
            if R & 1:
                R -= 1
                self.Data[R] = min([self.Data[R], x])
            L >>= 1; R >>= 1
    
    # k (0-indexed)
    def value(self, k):
        # インデックスを補正
        k += self.N
        res = self.Data[k]
        while k != 1:
            k >>= 1
            res = min(res, self.Data[k])
        return res


N, Q = map(int,input().split())
STX = [list(map(int,input().split())) for _ in range(N)]
D = [int(input()) for _ in range(Q)]

st = SegmentTree(Q)
for S, T, X in STX:
    l = bisect_left(D, S-X)
    r = bisect_left(D, T-X)
    st.update(l, r, X)

for k in range(Q):
    ans = st.value(k)
    if ans == inf:
        ans = -1
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect_left
inf = float('inf')

class SegmentTree:
    def __init__(self, N):
        tmp = 1
        while tmp < N:
            tmp <<= 1
        self.N = tmp
        self.data = [inf for _ in range(2*self.N-1)]
    
    def update(self, l, r, x):
        L = l + self.N - 1
        R = r + self.N - 1
        while L < R:
            if R & 1:
                R -= 1
                self.data[R] = min(self.data[R], x)
            if L & 1:
                self.data[L] = min(self.data[L], x)
                L += 1
            L >>= 1; R >>= 1
    
    def value(self, k):
        k += self.N - 1
        res = self.data[k]
        while k != 0:
            k >>= 1
            res = min(res, self.data[k])
        return res

N, Q = map(int,input().split())
STX = [list(map(int,input().split())) for _ in range(N)]
D = [int(input()) for _ in range(Q)]

st = SegmentTree(Q)
for S, T, X in STX:
    l = bisect_left(D, S-X)
    r = bisect_left(D, T-X)
    st.update(l, r, X)

for k in range(Q):
    ans = st.value(k)
    if ans == inf:
        ans = -1
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left


def main():
    N, Q, *I = map(int, open(0).read().split())
    STX, D = I[:3 * N], I[3 * N:]

    E = sorted(zip(*[iter(STX)] * 3), key=lambda x: x[2])

    R = [-1] * Q
    ans = [-1] * Q

    for s, t, x in E:
        l = bisect_left(D, s - x)
        r = bisect_left(D, t - x)
        while l < r:
            if R[l] == -1:
                ans[l] = x
                R[l] = r
                l += 1
            else:
                l = R[l]

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left


def main():
    N, Q, *I = map(int, open(0).read().split())
    STX, D = I[:3 * N], I[3 * N:]

    E = sorted(zip(*[iter(STX)] * 3), key=lambda x: x[2])

    R = [-1] * Q
    ans = [-1] * Q

    for s, t, x in E:
        l = bisect_left(D, s - x)
        r = bisect_left(D, t - x)
        while l < r:
            if R[l] == -1:
                ans[l] = x
                R[l] = r
                l += 1
            else:
                l = R[l]

    print(*ans, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect_left
inf = float('inf')

N, Q = map(int,input().split())
STX = [list(map(int,input().split())) for _ in range(N)]
D = [int(input()) for _ in range(Q)]

res = 1
while res < Q:
    res <<= 1
N0 = res
data = [inf for _ in range(2*N0-1)]

def update(l, r, x):
    L = l + N0
    R = r + N0
    while L < R:
        if R & 1:
            R -= 1
            data[R] = min(data[R], x)
        if L & 1:
            data[L] = min(data[L], x)
            L += 1
        L >>= 1; R >>= 1

def value(k):
    k += N0
    res = data[k]
    while k != 0:
        k >>= 1
        res = min(res, data[k])
    return res


for S, T, X in STX:
    l = bisect_left(D, S-X)
    r = bisect_left(D, T-X)
    update(l, r, X)

for k in range(Q):
    ans = value(k)
    if ans == inf:
        ans = -1
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC128 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,q = LI()
stx = [LI() for _ in range(n)]
stx.sort(key = itemgetter(2))
d = [I() for _ in range(q)]
ans = [-1]*q
skip = [-1]*q
for s,t,x in stx:
    l,r = bl(d,s-x),bl(d,t-x)
    while l < r:
        if skip[l] == -1:
            skip[l] = r
            ans[l] = x
            l += 1
        else:
            l = skip[l]
print(*ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC128 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,q = LI()
stx = [LI() for _ in range(n)]
stx.sort(key = itemgetter(2))
d = [I() for _ in range(q)]
ans = [-1]*(q+1)
right = [0]*q
for s,t,x in stx:
    l,r = bl(d,s-x),bl(d,t-x)
    #l≦d<rを満たすdがxでぶつかる
    #各dにおいて一番最初にぶつかるxを求めたい
    while l < r:
        while ans[l] != -1:
            l = right[l]
        if r <= l:
            break
        ans[l] = x
        right[l] = r
        l += 1
for i in ans[:-1]:
    print(i)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from heapq import heappush, heappop
from collections import defaultdict

N,Q = map(int,readline().split())
data = list(map(int,read().split()))
S = data[:3*N:3]
T = data[1:3*N:3]
X = data[2:3*N:3]
D = data[3*N:]

event = []
event += [(s-x,1,x) for x,s in zip(X,S)] # xに通行止めを1つ追加
event += [(t-x,2,x) for x,t in zip(X,T)] # xの通行止めを1つ削除
event += [(x,3,i) for i,x in enumerate(D)] # 最小の通行止めを答える

event.sort()

INF = 10**10
q = [INF]
counter = defaultdict(int)
counter[INF] = 1

answer = [None] * Q
for a,b,c in event:
    if b == 1:
        heappush(q,c)
        counter[c] += 1
    elif b == 2:
        counter[c] -= 1
    else:
        while counter[q[0]] == 0:
            heappop(q)
        x = q[0]
        if x == INF:
            x = -1
        answer[c] = x

print('\n'.join(map(str,answer)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline


class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

    # i+1番目からR番目まで足すとt以上となるような最小のRを返す
    def bisect_plus(self, i, t):
        L = i
        R = self.size
        R_prev = R
        sum_i = self.sum(i)
        while True:
            range_sum = self.sum(R) - sum_i
            if range_sum < t:
                if R == self.size:
                    return self.size + 1
                L, R = R, R_prev
            else:
                R_prev = R
                R = (L + R + 1) // 2
                if R == R_prev:
                    return R

    # L番目からi-1番目まで足すとt以上となるような最小のRを返す
    def bisect_minus(self, i, t):
        L = 1
        R = i
        L_prev = L
        sum_i = self.sum(i - 1)
        while True:
            range_sum = sum_i - self.sum(L - 1)
            if range_sum < t:
                if L == 1:
                    return 0
                L, R = L_prev, L
            else:
                L_prev = L
                L = (L + R) // 2
                if L == L_prev:
                    return L


def main():
    N, Q = map(int, input().split())
    ev = []
    x_list = []
    for _ in range(N):
        s, t, x = map(int, input().split())
        ev.append([s-x, 1, x])
        ev.append([t-x, -1, x])
        x_list.append(x)
    for _ in range(Q):
        d = int(input())
        ev.append([d, 0, 0])
    ev.sort(key=lambda p: p[0])
    x_list.sort()
    x_idx = {}
    for i in range(1, N+1):
        x_idx[x_list[i-1]] = i

    bit = Bit(N)
    x_list.append(-1)
    for pos, flag, x in ev:
        if flag == 0:
            print(x_list[bit.bisect_plus(0, 1) - 1])
        else:
            idx = x_idx[x]
            bit.add(idx, flag)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
n,q=map(int,input().split())
import heapq
S=[]
D=dict()
for i in range(n):
  s,t,x=map(int,input().split())
  S.append((1,x,max(0,s-x)))
  S.append((-1,x,max(0,t-x)))
  D[x]=False
S.sort(key=lambda x:x[2])
X=[]
cur=0
for i in range(q):
  d=int(input())
  while cur<2*n:
    a,b,c=S[cur]
    if c>d:
      break
    else:
      cur+=1
      if a==1:
        heapq.heappush(X,b)
        D[b]=True
      else:
        D[b]=False
  while X:
    ans=heapq.heappop(X)
    if D[ans]:
      print(ans)
      heapq.heappush(X,ans)
      break
  if not X:
    print(-1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n,q=map(int,input().split())
import heapq
S=[]
D=dict()
for i in range(n):
  s,t,x=map(int,input().split())
  S.append((1,x,max(0,s-x)))
  S.append((-1,x,max(0,t-x)))
  D[x]=False
S.sort(key=lambda x:x[2])
X=[]
cur=0
for i in range(q):
  d=int(input())
  while cur<2*n:
    a,b,c=S[cur]
    if c>d:
      break
    else:
      cur+=1
      if a==1:
        heapq.heappush(X,b)
        D[b]=True
      else:
        D[b]=False
  while X:
    ans=heapq.heappop(X)
    if D[ans]:
      print(ans)
      heapq.heappush(X,ans)
      break
  if not X:
    print(-1)