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: Time Limit Exceeded

Solution code:
import heapq
class HeapDict:
    def __init__(self):
        self.h = []
        self.d = {}

    def insert(self,x):
        if x not in self.d or self.d[x] == 0:
            heapq.heappush(self.h, x)
        self.d.setdefault(x,0)
        self.d[x] += 1


    def erase(self,x):
        if x not in self.d or self.d[x] == 0:
            return
        else:
            self.d[x] -= 1

        while self.h:
            if self.d[self.h[0]] == 0:
                heapq.heappop(self.h)
            else:
                break


    def get_min(self):
        if not self.h:
            return None
        else:
            return self.h[0]


    def pop(self):
        poped_val = self.h[0]
        self.erase(poped_val)
        return poped_val


    def exist(self, x):
        return (x in self.d and self.d[x] > 0)


    def show_h(self):
        elems = [v for v in self.h if self.d[v] > 0]
        print(elems)


    def show_d(self):
        print(self.d)



def main():
    n,q = map(int, input().split())
    eventl = []

    for _ in range(n):
        s,t,x = map(int, input().split())
        eventl.append((s-x, 'a-stop', x)) 
        eventl.append((t-x, 'b-start', x))

    for i in range(q):
        d = int(input())
        eventl.append((d,'c-go', i))

    eventl.sort()

    ans = [0]*q
    hd = HeapDict()
    for e in eventl:
        if e[1] == 'a-stop':
            hd.insert(e[2])
        elif e[1] == 'b-start':
            hd.erase(e[2])
        else:
            min_x = hd.get_min()
            if min_x is not None:
                ans[e[2]] = min_x
            else:
                ans[e[2]] = -1

    for a in ans:
        print(a)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq
class HeapDict:
    def __init__(self):
        self.h = []
        self.d = {}

    def insert(self,x):
        if x not in self.d or self.d[x] == 0:
            heapq.heappush(self.h, x)
        self.d.setdefault(x,0)
        self.d[x] += 1


    def erase(self,x):
        if x not in self.d or self.d[x] == 0:
            return
        else:
            self.d[x] -= 1

        while self.h:
            if self.d[self.h[0]] == 0:
                heapq.heappop(self.h)
            else:
                break


    def get_min(self):
        if not self.h:
            return None
        else:
            return self.h[0]


    def pop(self):
        poped_val = self.h[0]
        self.erase(poped_val)
        return poped_val


    def exist(self, x):
        return (x in self.d and self.d[x] > 0)


    def show_h(self):
        elems = [v for v in self.h if self.d[v] > 0]
        print(elems)


    def show_d(self):
        print(self.d)


def main():
    n,q = map(int, input().split())
    eventl = []

    for _ in range(n):
        s,t,x = map(int, input().split())
        eventl.append((s-x-0.5, 'stop', x)) 
        eventl.append((t-x-0.5, 'start', x))

    for i in range(q):
        d = int(input())
        eventl.append((d,'go', i))

    eventl.sort()

    ans = [0]*q
    hd = HeapDict()
    for e in eventl:
        if e[1] == 'stop':
            hd.insert(e[2])
        elif e[1] == 'start':
            hd.erase(e[2])
        else:
            min_x = hd.get_min()
            if min_x is not None:
                ans[e[2]] = min_x
            else:
                ans[e[2]] = -1

    for a in ans:
        print(a)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq
class HeapDict:
    def __init__(self):
        self.h = []
        self.d = {}

    def insert(self,x):
        if x not in self.d or self.d[x] == 0:
            heapq.heappush(self.h, x)
        self.d.setdefault(x,0)
        self.d[x] += 1


    def erase(self,x):
        if x not in self.d or self.d[x] == 0:
            return
        else:
            self.d[x] -= 1

        while self.h:
            if self.d[self.h[0]] == 0:
                heapq.heappop(self.h)
            else:
                break


    def get_min(self):
        if not self.h:
            return None
        else:
            return self.h[0]


    def pop(self):
        poped_val = self.h[0]
        self.erase(poped_val)
        return poped_val


    def exist(self, x):
        return (x in self.d and self.d[x] > 0)


    def show_h(self):
        elems = [v for v in self.h if self.d[v] > 0]
        print(elems)


    def show_d(self):
        print(self.d)

n,q = map(int, input().split())
eventl = []

for _ in range(n):
    s,t,x = map(int, input().split())
    eventl.append((s-x-0.5, 'stop', x)) 
    eventl.append((t-x-0.5, 'start', x))

for i in range(q):
    d = int(input())
    eventl.append((d,'go', i))

eventl.sort()

ans = [0]*q
hd = HeapDict()
for e in eventl:
    if e[1] == 'stop':
        hd.insert(e[2])
    elif e[1] == 'start':
        hd.erase(e[2])
    else:
        min_x = hd.get_min()
        if min_x is not None:
            ans[e[2]] = min_x
        else:
            ans[e[2]] = -1

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
import bisect
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))

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

event.sort()
now = []

tmp = 0
for i, (t, flg, x) in enumerate(event):
    if flg == 1:
        bisect.insort_left(now, x)
    else:
        idx = bisect.bisect_left(now, x)
        now.pop(idx)

    while tmp < q and i < len(event) - 1 and t <= d[tmp] < event[i+1][0]:
        if len(now) > 0:
            print(now[0])
        else:
            print(-1)
        tmp += 1

while tmp < q:
    print(-1)
    tmp += 1

Submission status: Time Limit Exceeded

Solution code:
import bisect
 
 
class SegTree:
 
    def __init__(self, n):
        # supposed that n = 2**m
        self.n = n
        self.val = [-1] * (2 * n - 1)
 
    def _update(self, a, b, v, k, l, r):
        if r <= a or b <= l:
            return
        if a <= l and r <= b:
            self.val[k] = v
        else:
            self._update(a, b, v, 2 * k + 1, l, (l + r) // 2)
            self._update(a, b, v, 2 * k + 2, (l + r) // 2, r)
 
    def update(self, a, b, v):
        # 区間[a, b)上の値をvに更新
        self._update(a, b, v, 0, 0, self.n)
 
    def query(self, x):
        # ノードxの値を返す
        k = self.n + x - 1
        ret = self.val[k]
        while k > 0:
            k = (k - 1) // 2
            ret = max(ret, self.val[k])
        return ret
 
 
def main():
    N, Q = list(map(int, input().split(' ')))
    work_list = [0] * N
    for n in range(N):
        work_list[n] = list(map(int, input().split(' ')))
    # 工事は出発地から遠い順に並べておく
    work_list.sort(key=lambda work: work[2], reverse=True)
    D = [0] * Q
    for q in range(Q):
        D[q] = int(input())
    # 一番最初に引っかかる工事のインデックスを求める
    QQ = 1
    while QQ < Q:
        QQ <<= 1
    tree = SegTree(QQ)
    for w, work in enumerate(work_list):
        s, t, x = work
        # s - x <= d < t - x だと工事に引っかかる
        left = bisect.bisect_left(D, s - x)
        right = bisect.bisect_left(D, t - x)
        tree.update(left, right, w)
    for q in range(Q):
        w = tree.query(q)
        if w == -1:
            print(-1)
        else:
            print(work_list[w][2])
 
 
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect


class SegTree:

    def __init__(self, n):
        # supposed that n = 2**m
        self.n = n
        self.val = [-1] * (2 * n - 1)

    def _update(self, a, b, v, k, l, r):
        if r <= a or b <= l:
            return
        if a <= l and r <= b:
            self.val[k] = v
        else:
            self._update(a, b, v, 2 * k + 1, l, (l + r) // 2)
            self._update(a, b, v, 2 * k + 2, (l + r) // 2, r)

    def update(self, a, b, v):
        # 区間[a, b)上の値をvに更新
        self._update(a, b, v, 0, 0, self.n)

    def query(self, x):
        # ノードxの値を返す
        k = self.n + x - 1
        ret = self.val[k]
        while k > 0:
            k = (k - 1) // 2
            ret = max(ret, self.val[k])
        return ret


def main():
    N, Q = list(map(int, input().split(' ')))
    work_list = list()
    for _ in range(N):
        work_list.append(list(map(int, input().split(' '))))
    # 工事は出発地から遠い順に並べておく
    work_list.sort(key=lambda work: work[2], reverse=True)
    D = list()
    for _ in range(Q):
        D.append(int(input()))
    # 一番最初に引っかかる工事のインデックスを求める
    QQ = 1
    while QQ < Q:
        QQ <<= 1
    tree = SegTree(QQ)
    for w, work in enumerate(work_list):
        s, t, x = work
        # s - x <= d < t - x だと工事に引っかかる
        left = bisect.bisect_left(D, s - x)
        right = bisect.bisect_left(D, t - x)
        tree.update(left, right, w)
    for q in range(Q):
        w = tree.query(q)
        if w == -1:
            print(-1)
        else:
            print(work_list[w][2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect


class SegTree:

    def __init__(self, n):
        # supposed that n = 2**m
        self.n = n
        self.val = [-1] * (2 * n - 1)

    def _update(self, a, b, v, k, l, r):
        if r <= a or b <= l:
            return
        if a <= l and r <= b:
            self.val[k] = v
        else:
            self._update(a, b, v, 2 * k + 1, l, (l + r) // 2)
            self._update(a, b, v, 2 * k + 2, (l + r) // 2, r)

    def update(self, a, b, v):
        # 区間[a, b)上の値をvに更新
        self._update(a, b, v, 0, 0, self.n)

    def query(self, x):
        # ノードxの値を返す
        k = self.n + x - 1
        ret = self.val[k]
        while k > 0:
            k = (k - 1) // 2
            ret = max(ret, self.val[k])
        return ret


def main():
    N, Q = list(map(int, input().split(' ')))
    work_list = [list(map(int, input().split(' '))) for _ in range(N)]
    # 工事は出発地から遠い順に並べておく
    work_list.sort(key=lambda work: work[2], reverse=True)
    D = [int(input()) for _ in range(Q)]
    # 一番最初に引っかかる工事のインデックスを求める
    QQ = 1
    while QQ < Q:
        QQ <<= 1
    tree = SegTree(QQ)
    for w, work in enumerate(work_list):
        s, t, x = work
        # s - x <= d < t - x だと工事に引っかかる
        left = bisect.bisect_left(D, s - x)
        right = bisect.bisect_left(D, t - x)
        tree.update(left, right, w)
    for q in range(Q):
        w = tree.query(q)
        if w == -1:
            print(-1)
        else:
            print(work_list[w][2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect


class SegTree:

    def __init__(self, n):
        # supposed that n = 2**m
        INF = 10 ** 12
        self.n = n
        self.val = [INF] * (2 * n - 1)

    def _update(self, a, b, v, k, l, r):
        if r <= a or b <= l:
            return
        if a <= l and r <= b:
            self.val[k] = min(v, self.val[k])
        else:
            self._update(a, b, v, 2 * k + 1, l, (l + r) // 2)
            self._update(a, b, v, 2 * k + 2, (l + r) // 2, r)

    def update(self, a, b, v):
        # 区間[a, b)上の値がvより大きければvに更新
        self._update(a, b, v, 0, 0, self.n)

    def query(self, x):
        # ノードxの値を返す
        k = self.n + x - 1
        ret = self.val[k]
        while k > 0:
            k = (k - 1) // 2
            ret = min(ret, self.val[k])
        return ret


def main():
    N, Q = list(map(int, input().split(' ')))
    work_list = [list(map(int, input().split(' '))) for _ in range(N)]
    # 工事は出発地から近い順に並べておく
    work_list.sort(key=lambda work: work[2])
    D = [int(input()) for _ in range(Q)]
    # 一番最初に引っかかる工事のインデックスを求める
    QQ = 1
    while QQ < Q:
        QQ <<= 1
    tree = SegTree(QQ)
    for w, work in enumerate(work_list):
        s, t, x = work
        # s - x <= d < t - x だと工事に引っかかる
        left = bisect.bisect_left(D, s - x)
        right = bisect.bisect_left(D, t - x)
        tree.update(left, right, w)
    for q in range(Q):
        w = tree.query(q)
        if w >= N:
            print(-1)
        else:
            print(work_list[w][2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect


class SegTree:

    def __init__(self, n):
        # supposed that n = 2**m
        INF = 10 ** 12
        self.n = n
        self.val = [INF for _ in range(2 * n + 1)]

    def _update(self, a, b, v, k, l, r):
        if r <= a or b <= l:
            return
        if a <= l and r <= b:
            self.val[k] = min(v, self.val[k])
        else:
            self._update(a, b, v, 2 * k + 1, l, (l + r) // 2)
            self._update(a, b, v, 2 * k + 2, (l + r) // 2, r)

    def update(self, a, b, v):
        # 区間[a, b)上の値がvより大きければvに更新
        self._update(a, b, v, 0, 0, self.n)

    def query(self, x):
        # ノードxの値を返す
        k = self.n + x - 1
        ret = self.val[k]
        while k > 0:
            k = (k - 1) // 2
            ret = min(ret, self.val[k])
        return ret


def main():
    N, Q = list(map(int, input().split(' ')))
    work_list = [list(map(int, input().split(' '))) for _ in range(N)]
    # 工事は出発地から近い順に並べておく
    work_list.sort(key=lambda work: work[2])
    D = [int(input()) for _ in range(Q)]
    # 一番最初に引っかかる工事のインデックスを求める
    QQ = 1
    while QQ < Q:
        QQ <<= 1
    tree = SegTree(QQ)
    for w in range(N):
        s, t, x = work_list[w]
        # s - x <= d < t - x だと工事に引っかかる
        left = bisect.bisect_left(D, s - x)
        right = bisect.bisect_left(D, t - x)
        tree.update(left, right, w)
    for q in range(Q):
        w = tree.query(q)
        if w >= N:
            print(-1)
        else:
            print(work_list[w][2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect


class SegTree:

    def __init__(self, n):
        # supposed that n = 2**m
        INF = 10 ** 12
        self.n = n
        self.val = [INF for _ in range(2 * n + 1)]

    def _update(self, a, b, v, k, l, r):
        if r <= a or b <= l:
            return
        if a <= l and r <= b:
            self.val[k] = min(v, self.val[k])
        else:
            self._update(a, b, v, 2 * k + 1, l, (l + r) // 2)
            self._update(a, b, v, 2 * k + 2, (l + r) // 2, r)

    def update(self, a, b, v):
        # 区間[a, b)上の値がvより大きければvに更新
        self._update(a, b, v, 0, 0, self.n)

    def query(self, x):
        # ノードxの値を返す
        k = self.n + x - 1
        ret = self.val[k]
        while k > 0:
            k = (k - 1) // 2
            ret = min(ret, self.val[k])
        return ret


def main():
    N, Q = list(map(int, input().split(' ')))
    work_list = [list(map(int, input().split(' '))) for _ in range(N)]
    # 工事は出発地から近い順に並べておく
    work_list.sort(key=lambda work: work[2])
    D = [int(input()) for _ in range(Q)]
    # 一番最初に引っかかる工事のインデックスを求める
    QQ = 1
    while QQ < Q:
        QQ <<= 1
    tree = SegTree(QQ)
    for w in range(N):
        s, t, x = work_list[w]
        # s - x <= d < t - x だと工事に引っかかる
        left = bisect.bisect_left(D, s - x)
        right = bisect.bisect_left(D, t - x)
        tree.update(left, right, w)
    for q in range(Q):
        w = tree.query(q)
        if w >= N:
            print(-1)
        else:
            print(work_list[w][2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from bisect import bisect_left, bisect_right
INF = float("inf")


def main():
    N, Q = map(int, input().split())
    XST = [0]*N
    for i in range(N):
        s, t, x = map(int, input().split())
        XST[i] = (x, s-x, t-x)
    XST.sort(reverse=True)
    D = [0]*Q
    for i in range(Q):
        D[i] = int(input())
    stop = [-1]*Q
    # print(D)
    # Dはソートされている。ラッキー！
    for x, s, t in XST:
        # こっから！
        # print("[{}, {})".format(s, t))
        frm = bisect_left(D, s)
        # ここまで！
        to = bisect_left(D, t, lo=frm)
        # print(frm, to)
        for j in range(frm, to):
            stop[j] = x
    print(*stop, sep="\n")


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from operator import itemgetter

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


class SegmentTree:
    def __init__(self, n: int, segfunc, ide_ele):
        self.N0 = 1 << (n - 1).bit_length()
        self.ide_ele = ide_ele
        self.data = [ide_ele] * (2 * self.N0)
        self.segfunc = segfunc
    
    def build(self, init_value: list):
        for i, x in enumerate(init_value):
            self.data[i + self.N0 - 1] = x
        for i in range(self.N0 - 2, -1, -1):
            self.data[i] = self.segfunc(self.data[2 * i + 1], self.data[2 * i + 2])
    
    def update(self, k: int, x):
        k += self.N0 - 1
        ################################################################
        self.data[k] = x
        ################################################################
        while k:
            k = (k - 1) // 2
            self.data[k] = self.segfunc(self.data[k * 2 + 1], self.data[k * 2 + 2])
    
    def query(self, left: int, right: int):
        L = left + self.N0
        R = right + self.N0
        res = self.ide_ele
        ################################################################
        
        while L < R:
            if L & 1:
                res = self.segfunc(res, self.data[L - 1])
                L += 1
            if R & 1:
                R -= 1
                res = self.segfunc(res, self.data[R - 1])
            L >>= 1
            R >>= 1
        
        ################################################################
        return res


def solve():
    N, Q = map(int, rl().split())
    events = []
    xs = set()
    for _ in range(N):
        s, t, x = map(int, rl().split())
        events.append((t - x, 0, x))
        events.append((s - x, 1, x))
        xs.add(x)
    for _ in range(Q):
        d = int(rl())
        events.append((d, 2, -1))
    events.sort(key=itemgetter(0, 1))
    
    x_to_idx = {x: idx for idx, x in enumerate(sorted(xs))}
    M = len(xs)
    ide_ele = 10 ** 10
    seg_tree = SegmentTree(M, min, ide_ele)
    
    ans = []
    for _, com, pos in events:
        if com == 0:
            seg_tree.update(x_to_idx[pos], ide_ele)
        elif com == 1:
            seg_tree.update(x_to_idx[pos], pos)
        else:
            tmp = seg_tree.data[0]
            ans.append(tmp if tmp != ide_ele else -1)
    print(*ans, sep='\n')


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappush, heappop
from operator import itemgetter

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N, Q = map(int, rl().split())
    events = []
    for _ in range(N):
        s, t, x = map(int, rl().split())
        events.append((t - x, 0, x))
        events.append((s - x, 1, x))
    for _ in range(Q):
        d = int(rl())
        events.append((d, 2, -1))
    events.sort(key=itemgetter(0, 1))
    
    pos_set = set()
    pos_hq = []
    ans = []
    for _, com, pos in events:
        if com == 0:
            pos_set.remove(pos)
        elif com == 1:
            pos_set.add(pos)
            heappush(pos_hq, pos)
        else:
            while pos_hq:
                if pos_hq[0] not in pos_set:
                    heappop(pos_hq)
                else:
                    break
            ans.append(pos_hq[0] if pos_hq else -1)
    print(*ans, sep='\n')


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n,q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = {}
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    F[x] = 0
    E.append((s-x, x, 1))
    E.append((t-x, x, -1))
E.append((10**10, 10**10, 1))

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

j = 0
for i in range(q):
    # print(F,j)
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] += 1
            heappush(Q, E[j][1])
        else:
            F[E[j][1]] -= 1
        j += 1
    
    while len(Q) > 0 and F[Q[0]] == 0:
        _ = heappop(Q)
    if len(Q) == 0:
        print(-1)
    else:
        print(Q[0])

Submission status: Time Limit Exceeded

Solution code:
n,q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = {}
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    F[x] = 0
    E.append((s-x, x, 1))
    E.append((t-x, x, -1))
E.append((10**10, 10**10, 1))

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

j = 0
for i in range(q):
    # print(F,j)
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] += 1
            heappush(Q, E[j][1])
        else:
            F[E[j][1]] -= 1
        j += 1
    
    while len(Q) > 0 and F[Q[0]] == 0:
        _ = heappop(Q)
    if len(Q) == 0:
        print(-1)
    else:
        print(Q[0])

Submission status: Time Limit Exceeded

Solution code:
n,q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = {}
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    F[x] = 0
    E.append((s-x, x, 1))
    E.append((t-x, x, -1))
E.append((10**10, 10**10, 1))

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

for i in range(q):
    j = 0
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] = 1
            heappush(Q, E[j][1])
        else:
            F[E[j][1]] = 0
        j += 1
    
    while len(Q) > 0 and F[Q[0]] == 0:
        _ = heappop(Q)
    if len(Q) == 0:
        print(-1)
    else:
        print(Q[0])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n, q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = [0] * n
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    E.append([s-x, i, 1])
    E.append([t-x, i, -1])
E.append([10**10, 10**10, 1])

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

for i in range(q):
    j = 0
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] = 1
            heappush(Q, [A[E[j][1]][2], E[j][1]])
        else:
            F[E[j][1]] = 0
        j += 1
    
    while len(Q) > 0:
        ans = heappop(Q)
        if F[ans[1]] == 1:
            heappush(Q, ans)
            break
    if len(Q) == 0:
        print(-1)
    else:
        print(ans[0])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n, q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = {}
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    F[x] = 0
    E.append([s-x, x, 1])
    E.append([t-x, x, -1])
E.append([10**10, 10**10, 1])

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

for i in range(q):
    j = 0
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] = 1
            heappush(Q, E[j][1])
        else:
            F[E[j][1]] = 0
        j += 1
    
    while len(Q) > 0:
        ans = heappop(Q)
        if F[ans] == 1:
            heappush(Q, ans)
            break
    if len(Q) == 0:
        print(-1)
    else:
        print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = {}
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    F[x] = 0
    E.append([s-x, x, 1])
    E.append([t-x, x, -1])
E.append([10**10, 10**10, 1])

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

for i in range(q):
    j = 0
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] = 1
            heappush(Q, E[j][1])
        else:
            F[E[j][1]] = 0
        j += 1
    
    while len(Q) > 0:
        ans = heappop(Q)
        if F[ans] == 1:
            heappush(Q, ans)
            break
    if len(Q) == 0:
        print(-1)
    else:
        print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,q = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
D = [int(input()) for i in range(q)]

E = []
F = {}
for i in range(n):
    s = A[i][0]
    t = A[i][1]
    x = A[i][2]
    F[x] = 0
    E.append([s-x, x, 1])
    E.append([t-x, x, -1])
E.append([10**10, 10**10, 1])

E.sort()

# print(E)

from heapq import heappush, heappop
Q = []

for i in range(q):
    j = 0
    while E[j][0] <= D[i]:
        if E[j][2] == 1:
            F[E[j][1]] = 1
            heappush(Q, E[j][1])
        else:
            F[E[j][1]] = 0
        j += 1
    
    while len(Q) > 0 and F[Q[0]] == 0:
        _ = heappop(Q)
    if len(Q) == 0:
        print(-1)
    else:
        print(Q[0])

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, Q = MAP()

event = [None]*(2*N+Q)
Xl = [0]*N
for i in range(N):
    S, T, X = MAP()
    event[2*i] = (S-X, 1, X)
    event[2*i+1] = (T-X, 0, X)
    Xl[i] = X

t = 2*N
for i in range(Q):
    D = INT()
    event[t+i] = (D, 2, 0)


event.sort()
p = []
q = []
for t, c, x in event:
    if c == 0:
        heappush(q, x)
    elif c == 1:
        heappush(p, x)
    else:
        while q and p[0] == q[0]:
            heappop(p)
            heappop(q)
        print(-1 if not p else p[0])

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

class BIT:
    def __init__(self, N):
        self.size = N
        self.tree = [0] * (N + 1)
        self.depth = N.bit_length()
 
    def _bitsum(self, i):
        ret = 0
        while i:
            ret += self.tree[i]
            i ^= i & -i
        return ret
 
    def bitsum(self, l, r=None):
        if r is None:
            return self._bitsum(l)
        else:
            return self._bitsum(r) - self._bitsum(l)
 
    def bitadd(self, i, x):
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
        return
 
    def lower_bound(self, x):
        sum_ = 0
        pos = 0
        v = 1 << self.depth
        for i in range(self.depth, -1, -1):
            k = pos + v
            if k <= self.size and sum_ + self.tree[k] < x:
                sum_ += self.tree[k]
                pos += v
            v >>= 1
        return pos

N, Q = MAP()

event = [None]*(2*N+Q)
Xl = [0]*N
for i in range(N):
	S, T, X = MAP()
	event[2*i] = (S-X, 1, X)
	event[2*i+1] = (T-X, 0, X)
	Xl[i] = X

t = 2*N
for i in range(Q):
	D = INT()
	event[t+i] = (D, 2, 0)

event.sort()
len_X = len(Xl)
Xl.sort()
zipped = {e:i for i, e in enumerate(Xl)}
bit = BIT(len_X+1)

for t, c, x in event:
	if c == 0:
		bit.bitadd(zipped[x], -1)
	elif c == 1:
		bit.bitadd(zipped[x], 1)
	else:
		idx = bit.lower_bound(1)
		print(-1 if idx > len_X else Xl[idx])