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:
#! /usr/bin/env python3
#! /usr/bin/env python3
import bisect
import sys
sys.setrecursionlimit(10**9)



# Ref: https://qiita.com/takayg1/items/b7b3f7d458915bcc7a4e
class LazySegTree:
    def __init__(self, init_val, segfunc, ide_ele = 2**31 - 1):
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.data = [ide_ele] * 2 * self.num
        self.lazy = [None] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.data[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.data[i] = self.segfunc(self.data[2 * i], self.data[2 * i + 1])



    def propagates(self, *ids):
        for i in reversed(ids):
            v = self.lazy[i]
            if v is None:
                continue
            self.lazy[2 * i] = v
            self.lazy[2 * i + 1] = v
            self.data[2 * i] = v
            self.data[2 * i + 1] = v
            self.lazy[i] = None

    def update(self, l, r, x): # [l, r)
        *ids, = self.gindex(l, r)
        self.propagates(*ids)
        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                self.lazy[l] = x
                self.data[l] = x
                l += 1
            if r & 1:
                self.lazy[r - 1] = x
                self.data[r - 1] = x
            r >>= 1
            l >>= 1
        for i in ids:
            self.data[i] = self.segfunc(self.data[2 * i], self.data[2 * i + 1])


    def query(self, l, r): # [l, r)
        *ids, = self.gindex(l, r)
        self.propagates(*ids)

        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.data[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.data[r - 1])
            l >>= 1
            r >>= 1
        return res

    def gindex(self, l, r):
        l += self.num
        r += self.num
        lm = l >> (l & -l).bit_length()
        rm = r >> (r & -r).bit_length()

        while r > l:
            if l <= lm:
                yield l
            if r <= rm:
                yield r
            r >>= 1
            l >>= 1
        while l:
            yield l
            l >>= 1

def zarts(D,x): # 座標圧縮
    return bisect.bisect_left(D,x)
    

INF=10**20
def solve(N: int, Q: int, S: "List[int]", T: "List[int]", X: "List[int]", D: "List[int]"):

    def segfunc(x,y):
        return min(x,y)

    v = [INF] * (len(D) + N + 1)

    seg = LazySegTree(v,segfunc,ide_ele=INF)

    _X = list(enumerate(X))
    _X.sort(key=lambda x:x[1],reverse=True)
    for i,x in _X:
        l = zarts(D,S[i]-X[i])
        r = zarts(D,T[i]-X[i])
        
        seg.update(l,r,X[i])
    

    for q in range(Q):
        d = q
        # print("d",d)
        x = seg.query(d,d+1)
        if x == INF:
            x = -1

        print(x)
    
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    S = [int()] * (N)  # type: "List[int]"
    T = [int()] * (N)  # type: "List[int]"
    X = [int()] * (N)  # type: "List[int]"
    # X = [(int(),int())] * (N)  # type: "List[int]"
    for i in range(N):
        S[i] = int(next(tokens))
        T[i] = int(next(tokens))
        X[i] = int(next(tokens))
        # X[i] = (-1 * int(next(tokens)),i)
    D = [int(next(tokens)) for _ in range(Q)]  # type: "List[int]"
    solve(N, Q, S, T, X, D)



if __name__ == "__main__":
    main()

Submission status: Runtime Error

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, 1))
                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()
            node.bal += key
            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 key == 1:
                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, 1))
                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.val = min_node.val
            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 key == 1:
            pre.left = cnode
        else:
            pre.right = cnode
        
        # バランス調整
        while q:
            new_node = None
            node, key = q.pop()
            node.bal -= key
            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 key == 1:
                    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())
e = []
for i in range(n):
  s,t,x = map(int, input().split())
  e.append((s-x,x,i))
  e.append((t-x,x,i))
e.sort(key=lambda x:x[0])
D = [int(input()) for _ in range(q)]
avl = AVLtree()
ans = []
f = [0]*n
j = 0
N = 2*n
for d in D:
  while j < N and e[j][0] <= d:
    _,x,i = e[j]
    if f[i]:
      avl.erase((x,i))
    else:
      avl.insert((x,i))
      f[i] = 1
    j += 1
  m = avl.lower_bound((-float("inf"),0))
  ans.append(m[0] if m != float("inf") else -1)

for i in ans:
  print(i)

Submission status: Runtime Error

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.val = min_node.val
            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.pop()
                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)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from heapq import heappush,heappop

# map(int, input().split())
N, Q = map(int, input().split())
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 i in range(Q):
    d = int(input())
    events.append((d, 2, i))

events = sorted(events)

q = [INF]
cnt = defaultdict(int)
ans = [INF]*Q
for a,b,c in events:
    if b == 0:
        heappush(q,c)
        cnt[c] += 1
    elif b==1:
        cnt[c] -= 1
    else:
        while len(q) > 1 and cnt[q[0]] == 0:
            heappop(q)
        if q[0] == INF:
            ans[c] = -1
        else:
            ans[c] = q[0]
for a in ans:
    print(a)

Submission status: Runtime Error

Solution code:
from collections import deque
N,M = map(int, input().split())
S = input() # len(S)=S+1 !!!
A = [-1 for _ in range(N+1)]
S = S[::-1]
for i in range(N+1):
  if S[i] == "1":
    continue
  flg = True
  for m in range(1,M+1):
    if i + m > N:
      A[i] = N
      flg = False
      break
    if S[i+m] == "0":
      A[i] = i+m
      flg = False
    else:
      continue
  if flg:
    print(-1)
    exit(0)
#print(A)
i = 0
ANS = []
while i < N :
  nxt = A[i]
  ANS.append(nxt - i)
  i = nxt
  
print(" ".join(map(str,ANS[::-1])))

Submission status: Runtime Error

Solution code:
import sys
from heapq import *
input = sys.stdin.readline

def main():
    n, q = map(int, input().split())
    
    key = []
    for i in range(n):
        s, t, x = map(int, input().split())
        l, r = max(0, s-x), max(0, t-x)
        key.append((l, -1, x))
        key.append((r, 1, x))

    key.sort()
    judge = []
    now = set()
    already = dict()
    search = []
    
    for i in range(n*2):
        s, j, x = key[i]
        
        if j == -1:
            heappush(judge, x)
            now.add(x)
        else:
            now.remove(x)
            if x in already:
                already[x] += 1
            else:
                already[x] = 1
        
        if i == n*2-1 or key[i][0] != key[i+1][0]:
            while judge:
                if judge[0] in already and already[judge[0]] > 0:
                    already[judge[0]] -= 1
                    heappop(judge)
                else:
                    break
            if judge:
                search.append((s, judge[0]))
            else:
                search.append((s, -1))

    size = len(search)
    index = 0
    answer = []
    for i in range(q):
        d = int(input())
        while index < size-1:
            if search[index+1][0] <= d:
                index += 1
            else:
                break
        print(search[index][1])

    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from heapq import *
input = sys.stdin.readline

def main():
    n, q = map(int, input().split())
    
    key = []
    for i in range(n):
        s, t, x = map(int, input().split())
        l, r = max(0, s-x), max(0, t-x)
        key.append((l, 1, x))
        key.append((r, -1, x))

    key.sort()
    judge = []
    now = set()
    already = dict()
    search = []
    
    for i in range(n*2):
        s, j, x = key[i]
        
        if j == 1:
            heappush(judge, x)
            now.add(x)
        else:
            now.remove(x)
            if x in already:
                already[x] += 1
            else:
                already[x] = 1
        
        if i == n*2-1 or key[i][0] != key[i+1][0]:
            while judge:
                if judge[0] in already and already[judge[0]] > 0:
                    already[judge[0]] -= 1
                    heappop(judge)
                else:
                    break
            if judge:
                search.append((s, judge[0]))
            else:
                search.append((s, -1))

    size = len(search)
    index = 0
    answer = []
    for i in range(q):
        d = int(input())
        while index < size-1:
            if search[index+1][0] <= d:
                index += 1
            else:
                break
        print(search[index][1])

    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from heapq import *
input = sys.stdin.readline

def main():
    n, q = map(int, input().split())
    
    key = []
    for i in range(n):
        s, t, x = map(int, input().split())
        l, r = max(0, s-x), max(0, t-x)
        key.append((l, 1, x))
        key.append((r, -1, x))

    key.sort()
    judge = []
    now = set()
    already = dict()
    
    index = 0
    ans = -1
    for i in range(q):
        d = int(input())
        for i in range(index, 2*n):
            s, j, x = key[i]
            if s > d:
                index = i
                break
            if j == 1:
                heappush(judge, x)
                now.add(x)
            else:
                now.remove(x)
                if x in already:
                    already[x] += 1
                else:
                    already[x] = 1
                    
                    
        while judge:
            if judge[0] in already and already[judge[0]] > 0:
                already[judge[0]] -= 1
                heappop(judge)
            else:
                break
        if judge:
            ans = judge[0]
        else:
            ans = -1      
            
        print(ans)

    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from heapq import *
input = sys.stdin.readline

def main():
    n, q = map(int, input().split())
    
    key = []
    for i in range(n):
        s, t, x = map(int, input().split())
        l, r = max(0, s-x), max(0, t-x)
        key.append((l, 1, x))
        key.append((r, -1, x))

    key.sort()
    judge = []
    now = set()
    already = dict()
    
    index = 0
    ans = -1
    for i in range(q):
        d = int(input())
        for i in range(index, 2*n):
            s, j, x = key[i]
            if s > d:
                index = i
                break
            if j == 1:
                heappush(judge, x)
                now = now.add(x)
            else:
                now.discard(x)
                if x in already:
                    already[x] += 1
                else:
                    already[x] = 1
                    
                    
        while judge:
            if judge[0] in already and already[judge[0]] > 0:
                already[judge[0]] -= 1
                heappop(judge)
            else:
                break
        if judge:
            ans = judge[0]
        else:
            ans = -1      
            
        print(ans)

    
if __name__ == "__main__":
    main()