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: Runtime Error

Solution code:
from heapq import heappush, heappop
import sys, os
from __pypy__ import builders
readline = sys.stdin.readline
N, Q = map(int, readline().split())
qs = [0]*N
for i in range(N):
    s, t, x = map(int, readline().split())
    qs[i] = (s-x, t-x, x)
qs.sort()

b = builders.BytesBuilder(Q)
que = []
D = [int(readline()) for i in range(Q)]
j = 0
for d in D:
    while j < N and qs[j][0] <= d:
        s, t, x = qs[j]
        heappush(que, (x, t))
        j += 1
    while que and que[0][1] <= d:
        heappop(que)
    if que:
        b.append(b"%d\n" % que[0][0])
    else:
        b.append(b"-1\n")
os.write(1, b.build())

Submission status: Runtime Error

Solution code:
List_S.sort(key=lambda x:x[0])
List_S.sort(key=lambda x:x[2])

n = N

for i in range(Q):
    flag = 0
    count = 0
    for j in range(n):
        if List_S[j-count][1] - 0.5 < List_D[i]:
            del List_S[j-count]
            count += 1
        elif (List_S[j-count][0] - 0.5 < (List_D[i] + List_S[j-count][2])) and ((List_D[i] + List_S[j-count][2]) < List_S[j-count][1]-0.5):
            print("{}".format(List_S[j-count][2]))
            flag = 1
            break
    n = n - count
    if flag == 0:
        print("-1")

Submission status: Runtime Error

Solution code:
#if 1

#include <bits/stdc++.h>
using namespace std;
int n,q;
vector <pair <int,pair <int,int> > > a;
multiset <int> s;

int main()
{
    scanf("%d %d", &n, &q);
    int t,ss,x;
    for(int i = 1;i <= n;i++)
    {
        scanf("%d %d %d", &ss, &t, &x);
        a.push_back({ss-x,{1,x}});
        a.push_back({t-x,{-1,x}});
    }
    int i = 0;
    sort(a.begin(),a.end());
    while(q--)
    {
        int d;
        scanf("%d",&d);
        while(a[i].first <= d&&i < a.size())
        {
            if(a[i].second.first == 1)
            {
                s.insert(a[i].second.second);
            }
            else
            {
                s.erase(a[i].second.second);
            }
            i++;
        }
        if(s.size() > 0) printf("%d\n",*s.begin());
        else printf("-1\n");
    }
}

#endif // 1++

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
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 II(): return int(sys.stdin.readline())
def SI(): return input()
from bisect import bisect

def main():
    N, Q = LI()
    XST = []
    ts = []
    for _ in range(N):
        s, t, x = LI()
        s -= x
        t -= x
        XST.append([x, s, t])
        ts.append(s)
        ts.append(t)
    ts.sort()
    ts.append(INF)
    D = []
    for _ in range(Q):
        D.append(II())
    xs = [INF] * (N * 2 + 1)
    XST.sort(reverse=True)
    for x, s, t in XST:
        s0 = bisect(ts, s)
        t0 = bisect(ts, t)
        for i in range(s0, t0):
            xs[i] = x
    for d in D:
        y = bisect(ts, d)
        y = xs[y]
        if y == INF:
            y = -1
        print(y)
        ts = ts[y:]
        xs = xs[y:]
    return

main()

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())

events = []
for _ in range(N):
    s, t, x = map(int, input().split())
    events.append((max(s-x, 0), 1, x))
    events.append((max(t-x, 0), -1, x))

D = []
for _ in range(Q):
    D.append(int(input()))
    
events = sorted(events, key=lambda x:x[0])

#print(events)
#print(D)

stopped = set([])
idx = 0
for t, command, x in events:
    if idx >= Q:
        break
    while D[idx] < t:
        print(min_x)
        idx += 1

    if command == 1:
        stopped.add(x)
    else:
        stopped.remove(x)
    #print(stopped)

    if len(stopped) == 0:
        min_x = -1
    else:
        min_x = min(stopped)

    #print(stopped)

for _ in range(idx, Q):
    print(min_x)

Submission status: Runtime Error

Solution code:
import collections
def main():
    range = xrange
    from sys import stdin, stdout
 
    def read():
        return stdin.readline().rstrip('\n')
 
    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)
 
    def read_int():
        return int(read())
 
    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]
 
    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)
 
    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)
 
    N, Q = [int(x) for x in input().split()]
    updates1 = []
    updates2 = []
    for i in range(N):
        S, T, X = [int(x) for x in input().split()]
        updates1.append((S - X, X))
        updates2.append((T - X, X))
 
    active = []
    to_delete = collections.defaultdict(int)
    import heapq
    heapq.heapify(updates1)
    heapq.heapify(updates2)
    for _ in range(Q):
        x = int(input())
        while updates1 and updates1[0][0] <= x:
            coord, val = heapq.heappop(updates1)
            heapq.heappush(active, val)
 
        while updates2 and updates2[0][0] <= x:
            coord, val = heapq.heappop(updates2)
            to_delete[val] += 1
 
        while active and to_delete[active[0]] > 0:
            to_delete[active[0]] -= 1
            heapq.heappop(active)
        write(active[0] if active else -1)
 
main()

Submission status: Runtime Error

Solution code:
import collections


def main():
    from sys import stdin, stdout

    read = iter(stdin.read().splitlines()).next
    #def read():
    #    return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    N, Q = [int(x) for x in input().split()]
    updates1 = []
    updates2 = []
    for i in range(N):
        S, T, X = [int(x) for x in input().split()]
        updates1.append((S - X, X))
        updates2.append((T - X, X))

    active = []
    to_delete = collections.defaultdict(int)
    import heapq
    heapq.heapify(updates1)
    heapq.heapify(updates2)
    for _ in range(Q):
        x = int(input())
        while updates1 and updates1[0][0] <= x:
            coord, val = heapq.heappop(updates1)
            heapq.heappush(active, val)

        while updates2 and updates2[0][0] <= x:
            coord, val = heapq.heappop(updates2)
            to_delete[val] += 1

        while active and to_delete[active[0]] > 0:
            to_delete[active[0]] -= 1
            heapq.heappop(active)
        write(active[0] if active else -1)

main()

Submission status: Runtime Error

Solution code:
import collections


def main():
    from sys import stdin, stdout

    read = iter(sys.stdin.read().splitlines()).next
    #def read():
    #    return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    N, Q = [int(x) for x in input().split()]
    updates1 = []
    updates2 = []
    for i in range(N):
        S, T, X = [int(x) for x in input().split()]
        updates1.append((S - X, X))
        updates2.append((T - X, X))

    active = []
    to_delete = collections.defaultdict(int)
    import heapq
    heapq.heapify(updates1)
    heapq.heapify(updates2)
    for _ in range(Q):
        x = int(input())
        while updates1 and updates1[0][0] <= x:
            coord, val = heapq.heappop(updates1)
            heapq.heappush(active, val)

        while updates2 and updates2[0][0] <= x:
            coord, val = heapq.heappop(updates2)
            to_delete[val] += 1

        while active and to_delete[active[0]] > 0:
            to_delete[active[0]] -= 1
            heapq.heappop(active)
        write(active[0] if active else -1)

main()

Submission status: Runtime Error

Solution code:
from sys import stdin
import numpypy as np
N, Q = [int(x) for x in stdin.readline().rstrip().split()]
STX = np.zeros((N, 3))
for i in range(N):
    STX[i, 0], STX[i, 1], STX[i, 2] = [int(x) for x in stdin.readline().rstrip().split()]
D = [int(input()) for _ in range(Q)]
STX = STX[np.argsort(STX[:, 2])]

for d in D:
    STX_copy = np.copy(STX)
    STX_copy[:, :2] = STX_copy[:, :2] - d
    try:
        print(int(STX_copy[np.where((STX_copy[:, 0] - 0.5 <= STX_copy[:, 2]) & (STX_copy[:, 1] - 0.5 >= STX_copy[:, 2]))][0, 2]))
    except:
        print(-1)

Submission status: Runtime Error

Solution code:
import numpy as np

N, Q = map(int, input().split())
STX = []
for i in range(N):
    S, T, X = map(int, input().split())
    STX.append([S, T, X])

STX = sorted(STX, key=lambda x:x[2], reverse=True)
STX = np.array(STX)
D = []
for i in range(Q):
    D.append(int(input()))

out = np.ones(max(STX[:, 2])) * -1
for S, T, X in STX:
    out[max(S-X, 0):max(T-X, 1)] = X
    
for i in D:
    print(int(out[i]))

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def gindex(l, r):
    L = l + N0; R = r + N0
    lm = (L // (L & -L)) >> 1
    rm = (R // (R & -R)) >> 1
    while L < R:
        if R <= rm:
            yield R
        if L <= lm:
            yield L
        L >>= 1; R >>= 1
    while L:
        yield L
        L >>= 1
 
def propagates(*ids):
    for i in reversed(ids):
        v = lazy[i-1]
        if v is None:
            continue
        lazy[2*i-1] = data[2*i-1] = lazy[2*i] = data[2*i] = v
        lazy[i-1] = None
 
def update(l, r, x):
    *ids, = gindex(l, r)
    propagates(*ids)
 
    L = N0 + l; R = N0 + r
    while L < R:
        if R & 1:
            R -= 1
            lazy[R-1] = data[R-1] = x
        if L & 1:
            lazy[L-1] = data[L-1] = x
            L += 1
        L >>= 1; R >>= 1
    for i in ids:
        data[i-1] = min(data[2*i-1], data[2*i])
 
def query(l, r):
    propagates(*gindex(l, r))
    L = N0 + l; R = N0 + r
 
    s = INF
    while L < R:
        if R & 1:
            R -= 1
            s = min(s, data[R-1])
        if L & 1:
            s = min(s, data[L-1])
            L += 1
        L >>= 1; R >>= 1
    return s


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

N=10000000
INF = 2**31-1
 
LV = (N-1).bit_length()
N0 = 2**LV
data = [INF]*(2*N0)
lazy = [None]*(2*N0)
 

a=[list(map(int,input().split())) for i in range(n)]
a.sort(key=lambda x:x[2],reverse=True)

a=[ [ max(0,a[i][0]-a[i][2]) , max(0,a[i][1]-a[i][2]) , a[i][2] ] for i in range(n)]

for i in range(n):
    l,r,x=a[i][0],a[i][1],a[i][2]
    update(l,r,x)

for i in range(Q):
    dp=int(input())
    ans=query(dp,dp+1)
    print(-1 if ans==INF else ans)

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def gindex(l, r):
    L = l + N0; R = r + N0
    lm = (L // (L & -L)) >> 1
    rm = (R // (R & -R)) >> 1
    while L < R:
        if R <= rm:
            yield R
        if L <= lm:
            yield L
        L >>= 1; R >>= 1
    while L:
        yield L
        L >>= 1
 
def propagates(*ids):
    for i in reversed(ids):
        v = lazy[i-1]
        if v is None:
            continue
        lazy[2*i-1] = data[2*i-1] = lazy[2*i] = data[2*i] = v
        lazy[i-1] = None
 
def update(l, r, x):
    *ids, = gindex(l, r)
    propagates(*ids)
 
    L = N0 + l; R = N0 + r
    while L < R:
        if R & 1:
            R -= 1
            lazy[R-1] = data[R-1] = x
        if L & 1:
            lazy[L-1] = data[L-1] = x
            L += 1
        L >>= 1; R >>= 1
    for i in ids:
        data[i-1] = min(data[2*i-1], data[2*i])
 
def query(l, r):
    propagates(*gindex(l, r))
    L = N0 + l; R = N0 + r
 
    s = INF
    while L < R:
        if R & 1:
            R -= 1
            s = min(s, data[R-1])
        if L & 1:
            s = min(s, data[L-1])
            L += 1
        L >>= 1; R >>= 1
    return s


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

N=1000000000
INF = 2**31-1
 
LV = (N-1).bit_length()
N0 = 2**LV
data = [INF]*(2*N0)
lazy = [None]*(2*N0)
 

a=[list(map(int,input().split())) for i in range(n)]
a.sort(key=lambda x:x[2],reverse=True)

a=[ [ max(0,a[i][0]-a[i][2]) , max(0,a[i][1]-a[i][2]) , a[i][2] ] for i in range(n)]

for i in range(n):
    l,r,x=a[i][0],a[i][1],a[i][2]
    update(l,r,x)

for i in range(Q):
    dp=int(input())
    ans=query(dp,dp+1)
    print(-1 if ans==INF else ans)

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def gindex(l, r):
    L = l + N0; R = r + N0
    lm = (L // (L & -L)) >> 1
    rm = (R // (R & -R)) >> 1
    while L < R:
        if R <= rm:
            yield R
        if L <= lm:
            yield L
        L >>= 1; R >>= 1
    while L:
        yield L
        L >>= 1
 
def propagates(*ids):
    for i in reversed(ids):
        v = lazy[i-1]
        if v is None:
            continue
        lazy[2*i-1] = data[2*i-1] = lazy[2*i] = data[2*i] = v
        lazy[i-1] = None
 
def update(l, r, x):
    *ids, = gindex(l, r)
    propagates(*ids)
 
    L = N0 + l; R = N0 + r
    while L < R:
        if R & 1:
            R -= 1
            lazy[R-1] = data[R-1] = x
        if L & 1:
            lazy[L-1] = data[L-1] = x
            L += 1
        L >>= 1; R >>= 1
    for i in ids:
        data[i-1] = min(data[2*i-1], data[2*i])
 
def query(l, r):
    propagates(*gindex(l, r))
    L = N0 + l; R = N0 + r
 
    s = INF
    while L < R:
        if R & 1:
            R -= 1
            s = min(s, data[R-1])
        if L & 1:
            s = min(s, data[L-1])
            L += 1
        L >>= 1; R >>= 1
    return s


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

N=1000000
INF = 2**31-1
 
LV = (N-1).bit_length()
N0 = 2**LV
data = [INF]*(2*N0)
lazy = [None]*(2*N0)
 

a=[list(map(int,input().split())) for i in range(n)]
a.sort(key=lambda x:x[2],reverse=True)

a=[ [ max(0,a[i][0]-a[i][2]) , max(0,a[i][1]-a[i][2]) , a[i][2] ] for i in range(n)]

for i in range(n):
    l,r,x=a[i][0],a[i][1],a[i][2]
    update(l,r,x)

for i in range(Q):
    dp=int(input())
    ans=query(dp,dp+1)
    print(-1 if ans==INF else ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import numpy as np

N, Q = map(int, input().split())
STX = []
for i in range(N):
    S, T, X = map(int, input().split())
    STX.append([S, T, X])

STX = sorted(STX, key=lambda x:x[2], reverse=True)
D = []
for i in range(Q):
    D.append(int(input()))

out = np.ones(max(D))
for S, T, X in STX:
    out[max(S-X, 0):max(T-X, 1)] = X

Submission status: Runtime Error

Solution code:
#D in [S_i-X_i,T_i-X_i) → Xiで止まる
import sys
input = sys.stdin.readline
from heapq import heappush,heappop

N,Q = map(int,input().split())
q = []

STX = [[int(x) for x in input().split()] for _ in range(N)]
for s,t,x in STX:
  heappush(q,(s-x,1,x)) # xで死ぬ
  heappush(q,(t-x,0,x)) # xで死ななくなる
  
D = [int(input()) for _ in range(Q)]
for i,d in enumerate(D):
  heappush(q,(d,2,i))
answer = [-1]*Q

se = set() # 引っかかってる場所

while q:
  a,c,b = heappop(q)
  if c == 2: # queryに答える
    if se:
      #answer[b] = min(se)
  elif c == 1:
    se.add(b)
  elif c == 0:
    se.remove(b)

    
for x in answer:
  print(x)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import math
import collections
import operator

N, Q = map(int, sys.stdin.readline().rstrip().split(" "))
events = []
for _ in range(N):
    S, T, X = map(int, sys.stdin.readline().rstrip().split(" "))
    events.append((S - X, X))
    events.append((T - X, -X))
events.sort(key=operator.itemgetter(0))
events = collections.deque(events)

pedestrians = []
for i in range(Q):
    D, = map(int, sys.stdin.readline().rstrip().split(" "))
    pedestrians.append((i, D))
pedestrians.sort(key=operator.itemgetter(1))
# pedestrians = collections.deque(pedestrians)

current_stops = set()
# current_pedestrian = pedestrians.pop(0)

results = []
for i, current_pedestrian in pedestrians:
    while True:
        if len(events) > 0 and events[0][0] <= current_pedestrian:
            event = events.popleft()
            # print(event)
            if event[1] >= 0:
                current_stops.add(event[1])
            else:
                current_stops.remove(-event[1])
        else:
            break
    # print(current_stops)
    if len(current_stops) > 0:
        stop = min(current_stops)
        # print(current_stops)
        # print(current_pedestrian, stop[2])
        results.append((i, stop))
    else:
        results.append((i, -1))
for i, result in sorted(results, key=operator.itemgetter(0)):
    print(result)

exit(0)

Submission status: Runtime Error

Solution code:
import collections

def main():
    N, Q = [int(x) for x in input().split()]
    updates = []
    for i in range(N):
        S, T, X = [int(x) for x in input().split()]
        updates.append((S-X, 1, X))
        updates.append((T-X, -1, X))
 
    active = []
    to_delete = collections.defaultdict(int)
    import heapq
    heapq.heapify(updates)
    for _ in range(Q):
        x = int(input())
        while updates and updates[0][0] <= x:
            coord, tp, val = heapq.heappop(updates)
 
            if tp == -1:
                to_delete[val] += 1
            else:
                heapq.heappush(active, val)
 
        while active and to_delete[active[0]] > 0:
            to_delete[active[0]] -= 1
            heapq.heappop(active)
        print active[0] if active else -1)

######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s:self.buffer.write(s.encode('ascii'))
            self.read = lambda:self.buffer.read().decode('ascii')
            self.readline = lambda:self.buffer.readline().decode('ascii')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()

Submission status: Runtime Error

Solution code:
import heapq
from collections import deque

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

ng = []
for _ in range(N):
    s, t, x = map(int, input().split())
    start = s - x if s > x else 0
    end = t - x if t > x else 0
    heapq.heappush(ng, (x, start, end, x))

q = []
for _ in range(Q):
    q.append(int(input()))

# print(ng)

second_ng = deque()
_, start, end, x = heapq.heappop(ng)
second_ng.append((start, end, x))
while len(ng) > 0:
    _, start, end, X = heapq.heappop(ng)
    flag = True
    for s, e, d in second_ng:
        # print((start, end, x, s, e, d))
        if e < start:
            continue
        elif s > end:
            continue
        elif s <= start and end <= e:
            flag = False
            break
        elif s <= start:
            start = e
        elif end <= e:
            end = s
        else:
            heapq.heappush((-X, e, end, X))
            end = s
    if flag:
        second_ng.append((start, end, X))

normalized_ng = []
while len(second_ng) > 0:
    heapq.heappush(normalized_ng, second_ng.popleft())

# print(normalized_ng)
# print(q)

start, end, x = heapq.heappop(normalized_ng)
for i in q:
    if i < start:
        print(-1)
    elif start <= i < end:
        print(x)
    else:
        flag = True
        while len(normalized_ng) > 0:
            start, end, x = heapq.heappop(normalized_ng)
            # print(start, end, x)
            if i < start:
                print(-1)
                flag = False
                break
            elif start <= i < end:
                print(x)
                flag = False
                break
        if flag:
            print(-1)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
class segtree:
    def __init__(self, nn):
        self.NN = nn
        self.XX = [0] * (2**(nn+1)-1)
    def getmax(self, i):
        j = 2**self.NN + i - 1
        ma = -1
        while j >= 0:
            ma = max(ma, self.XX[j])
            j = (j-1) // 2
        return -1 if ma <= 0 else INF - ma
    def updaterange(self, a, b, x):
        l = a + (1<<self.NN)
        r = b + (1<<self.NN)
        s = 0
        while l < r:
            if l%2:
                self.XX[l-1] = max(self.XX[l-1], x)
                l += 1
            if r%2:
                r -= 1
                self.XX[r-1] = max(self.XX[r-1], x)
            l >>= 1
            r >>= 1

N, Q = map(int, input().split())
st = segtree(18)
INF = 1<<50
for _ in range(N):
    s, t, x = map(int, input().split())
    st.updaterange(s-x, t-x, INF-x)
for _ in range(Q):
    print(st.getmax(int(input())))

Submission status: Runtime Error

Solution code:
class segtree:
    def __init__(self, nn):
        self.NN = nn
        self.XX = [0] * (2**(nn+1)-1)
    def getmax(self, i):
        j = 2**self.NN + i - 1
        ma = -1
        while j >= 0:
            ma = max(ma, self.XX[j])
            j = (j-1) // 2
        return -1 if ma <= 0 else INF - ma
    def updaterange(self, a, b, x):
        l = a + (1<<self.NN)
        r = b + (1<<self.NN)
        s = 0
        while l < r:
            if l%2:
                self.XX[l-1] = max(self.XX[l-1], x)
                l += 1
            if r%2:
                r -= 1
                self.XX[r-1] = max(self.XX[r-1], x)
            l >>= 1
            r >>= 1

N, Q = map(int, input().split())
st = segtree(17)
INF = 1<<50
for _ in range(N):
    s, t, x = map(int, input().split())
    st.updaterange(s-x, t-x, INF-x)
for _ in range(Q):
    print(st.getmax(int(input())))

Submission status: Runtime Error

Solution code:
import numpy as np

N, Q = map(int, input().split())
S = [0] * N
T = [0] * N
X = [0] * N

ex = []
for i in range(N):
	S[i], T[i], X[i] = map(int, input().split())
	S[i] -= X[i]
	T[i] -= X[i]
	ex.append((S[i], True, X[i]))
	ex.append((T[i], False, X[i]))

ex.append((1000000007, False, -1))
ex = sorted(ex, key=lambda e: e[0])
barricades = set()
i = 0
for q in range(Q):
	D = int(input())
	while ex[i][0] <= D:
		if ex[i][1]:
			barricades.add(ex[i][2])
		else:
			barricades.remove(ex[i][2])
		i += 1
	if 0 == len(barricades):
		print(-1)
	else:
		print(min(barricades))

Submission status: Runtime Error

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

N, Q = list(map(int, input().split()))
S = dict()

for i in range(N):
    s, t, x = list(map(int, input().split()))
    if (s - x) in S.keys():
        S[s - x] = (lambda y: (y[0] + 1, min(y[1], x)))(S[s - x])
    else:
        S[s-x] = (1, x)
    if (t - x) in S.keys():
        S[t - x] = (lambda y: (y[0] - 1, min(y[1], x)))(S[t - x])
    else:
        S[t-x] = (-1, x)

S = [(key, *S[key]) for key in sorted(S.keys())]
S += [(1e9+7, 0, 0)]

idx = 0
cum = 0
for i in range(Q):
    D = int(input())
    while S[idx][0] <= D:
        cum += S[idx][1]
        idx += 1
    if cum == 0:
        print("-1")
    else:
        print(S[idx][2])

Submission status: Runtime Error

Solution code:
import numpy as np
n,q=map(int,input().split())
dic={}
for i in range(n):
     s,t,x=map(int,input().split())
     try:
          dic[x].append((s,t))
     except:
          dic[x]=[(s,t)]
d=[]
for i in range(q):
     d.append(int(input()))
ma_d=max(d)
s_t=np.ones(ma_d+1)*-1
k=sorted(dic.keys())[::-1]
for x in k:
     for sts in dic[x]:
          s,t=sts
          s-=x
          t-=x
          if t<0:
               continue
          if s>ma_d:
               continue
          s_t[max(0,s):min(t,ma_d+1)]=x
for a in d:
     print(int(s_t[a]))

Submission status: Runtime Error

Solution code:
import numpy as np
n,q=map(int,input().split())
dic={}
for i in range(n):
     s,t,x=map(int,input().split())
     try:
          dic[x].append((s,t))
     except:
          dic[x]=[(s,t)]
d=[]
for i in range(q):
     d.append(int(input()))
ma_d=max(d)
s_t=np.ones(ma_d+1)*-1
k=sorted(dic.keys())[::-1]
for x in k:
     for sts in dic[x]:
          s,t=sts
          s-=x
          t-=x
          if t<0:
               continue
          s_t[max(0,s):min(t,ma_d+1)]=x
for a in d:
     print(int(s_t[a]))

Submission status: Runtime Error

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

N, Q = map(int, input().split())
SmXTmXX = [0] * N
for _ in range(N):
    s, t, x = map(int, input().split())
    SmXTmXX.append((s - x, t - x, x))
SmXTmXX.sort(lambda x: x[0])
# print(SmXTmXX)
D = [0] * Q
for i in range(Q):
    d = int(input())
    D[i] = d

ans = [-1] * Q
i = 0
for n in range(N):
    di, dj, x = SmXTmXX[n]
    if dj <= 0:
        continue
    i = bisect_left(D, di, i) if di > 0 else 0
    j = bisect_left(D, dj, i)
#     print(f"{i} to {j} is out")
    for k in range(i, j):
        ans[k] = x if ans[k] == -1 else min(ans[k], x)
        # print(f"marked {k} as {x}")
for v in ans:
    print(v)

Submission status: Runtime Error

Solution code:
import sys
input =sys.stdin.readline
N,Q =map(int,input().split())
lis =[[int(i)for i in input().split()]for _ in range(N)]
basyo =[[int(input()),-1,-1,True] for _ in range(Q)]
lis = sorted(lis,key = lambda x:-x[2])
if basyo[0][0]!= 0:
    basyo.insert([0,-1,-1,False])
basyo.append([10**9+1,-1,-1,False])
#basyo = [[0,-1,-1],[10**9+1,-1,-1]]#[start,end]
def nibun(li,x):
    def hantei(numb):
        if li[numb][0]>x:
            return True
        else:
            return False
    left = -1
    right =len(li)
    while right - left != 1:
        med = (left+right)//2
        if hantei(med):
            right = med
        else:
            left = med
    return left

for posi in lis:
    X =max(posi[0]-posi[2],0)
    ind = nibun(basyo,X)
    if basyo[ind][0]!=X:
        basyo.insert(ind+1,[X,posi[2],-1,False])
    else:
        basyo[ind][1]=posi[2]
    X =max(posi[1]-1-posi[2],0)
    ind =nibun(basyo,X)
    if basyo[ind][0]!=X:
        basyo.insert(ind+1,[X,-1,posi[2],False])
    else:
        basyo[ind][2]=posi[2]
if basyo[0][1]==basyo[0][2]:
    basyo[0][1]=-1
for i,j in enumerate(basyo):
    if j[-1]:
        foo = max(j[1:3])
        if foo==-1:
            print(basyo[i-1][1])
        else:
            print(foo)

Submission status: Runtime Error

Solution code:
import bisect
from operator import itemgetter

n, q = map(int, input().split())
stx = sorted([list(map(int, input().split())) for i in range(n)], key=itemgetter(2))
d = [int(input()) for i in range(q)]
stop = [-1 for i in range(q)]
did = 0
for i in stx:
    s = i[0] - i[2] - 0.5
    t = i[1] - i[2] - 0.5
    a = bisect.bisect_right(d[did:], t)
    b = bisect.bisect_right(d[did:], s)
    did += a - b
    for j in range(b + did, a + did):
        stop[j - 1] = i[2]
for i in stop:
    print(i)