Legacy (Codeforces 786B)
Tags: Others, shortest paths

Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them. There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial.  By default he can not open any portal by this gun. There are q plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.Plans on the website have three types:  With a plan of this type you can open a portal from planet v to planet u.  With a plan of this type you can open a portal from planet v to any planet with index in range [l, r].  With a plan of this type you can open a portal from any planet with index in range [l, r] to planet v. Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.

Input: The first line of input contains three integers n, q and s (1 ≤ n, q ≤ 105, 1 ≤ s ≤ n) — number of planets, number of plans and index of earth respectively.The next q lines contain the plans. Each line starts with a number t, type of that plan (1 ≤ t ≤ 3). If t = 1 then it is followed by three integers v, u and w where w is the cost of that plan (1 ≤ v, u ≤ n, 1 ≤ w ≤ 109). Otherwise it is followed by four integers v, l, r and w where w is the cost of that plan (1 ≤ v ≤ n, 1 ≤ l ≤ r ≤ n, 1 ≤ w ≤ 109).

Output: In the first and only line of output print n integers separated by spaces. i-th of them should be minimum money to get from earth to i-th planet, or  - 1 if it's impossible to get to that planet.

Note: In the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2.

Sample Inputs:
3 5 1
2 3 2 3 17
2 3 2 2 16
2 2 2 3 3
3 3 1 1 12
1 3 3 17

4 3 1
3 4 1 3 12
2 2 3 4 10
1 2 4 16

Sample Outputs:
0 28 12

0 -1 -1 12

Solution (Python):
import heapq
import sys
readline = sys.stdin.readline

class Segment_Tree:

    def __init__(self, N, f, e, lst=None):
        self.f = f
        self.e = e
        self.N = N
        if lst == None:
            self.segment_tree = [self.e] * 2 * self.N
        else:
            assert len(lst) <= self.N
            self.segment_tree = [self.e] * self.N + [x for x in lst] + [self.e] * (N - len(lst))
            for i in range(self.N - 1, 0, -1):
                self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def __getitem__(self, i):
        if type(i) == int:
            if -self.N <= i < 0:
                return self.segment_tree[i + self.N * 2]
            elif 0 <= i < self.N:
                return self.segment_tree[i + self.N]
            else:
                raise IndexError('list index out of range')
        else:
            (a, b, c) = (i.start, i.stop, i.step)
            if a == None or a < -self.N:
                a = self.N
            elif self.N <= a:
                a = self.N * 2
            elif a < 0:
                a += self.N * 2
            else:
                a += self.N
            if b == None or self.N <= b:
                b = self.N * 2
            elif b < -self.N:
                b = self.N
            elif b < 0:
                b += self.N * 2
            else:
                b += self.N
            return self.segment_tree[slice(a, b, c)]

    def __setitem__(self, i, x):
        if -self.N <= i < 0:
            i += self.N * 2
        elif 0 <= i < self.N:
            i += self.N
        else:
            raise IndexError('list index out of range')
        self.segment_tree[i] = x
        while i > 1:
            i >>= 1
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def Build(self, lst):
        for (i, x) in enumerate(lst, self.N):
            self.segment_tree[i] = x
        for i in range(self.N - 1, 0, -1):
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def Fold(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        vL = self.e
        vR = self.e
        while L < R:
            if L & 1:
                vL = self.f(vL, self.segment_tree[L])
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.segment_tree[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

    def Fold_Index(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        if L == R:
            return None
        x = self.Fold(L - self.N, R - self.N)
        while L < R:
            if L & 1:
                if self.segment_tree[L] == x:
                    i = L
                    break
                L += 1
            if R & 1:
                R -= 1
                if self.segment_tree[R] == x:
                    i = R
                    break
            L >>= 1
            R >>= 1
        while i < self.N:
            if self.segment_tree[i] == self.segment_tree[i << 1]:
                i <<= 1
            else:
                i <<= 1
                i |= 1
        i -= self.N
        return i

    def Interval_Decomp(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        interval_decomp = []
        while L < R:
            if R & 1:
                R -= 1
                interval_decomp.append(R)
            if L & 1:
                interval_decomp.append(L)
                L += 1
            L >>= 1
            R >>= 1
        interval_decomp.sort()
        return interval_decomp

    def __str__(self):
        return '[' + ', '.join(map(str, self.segment_tree[self.N:])) + ']'

class Graph:

    def __init__(self, V, edges=False, graph=False, directed=False, weighted=False, inf=float('inf')):
        self.V = V
        self.directed = directed
        self.weighted = weighted
        self.inf = inf
        if not graph:
            self.edges = edges
            self.graph = [[] for i in range(self.V)]
            if weighted:
                for (i, j, d) in self.edges:
                    self.graph[i].append((j, d))
                    if not self.directed:
                        self.graph[j].append((i, d))
            else:
                for (i, j) in self.edges:
                    self.graph[i].append(j)
                    if not self.directed:
                        self.graph[j].append(i)
        else:
            self.graph = graph

    def Dijkstra(self, s, route_restoration=False):
        dist = [self.inf] * self.V
        dist[s] = 0
        hq = [(0, s)]
        if route_restoration:
            parents = [None] * self.V
        while hq:
            (dx, x) = heapq.heappop(hq)
            if dist[x] < dx:
                continue
            for (y, dy) in self.graph[x]:
                if dist[y] > dx + dy:
                    dist[y] = dx + dy
                    if route_restoration:
                        parents[y] = x
                    heapq.heappush(hq, (dist[y], y))
        if route_restoration:
            return (dist, parents)
        else:
            return dist
(N, Q, s) = map(int, readline().split())
s -= 1
ST = Segment_Tree(N, min, 0)
graph = [[] for i in range(3 * N)]
for i in range(1, N):
    graph[i].append((2 * i, 0))
    graph[i].append((2 * i + 1, 0))
    if 2 * i < N:
        graph[2 * i + 2 * N].append((i + 2 * N, 0))
    else:
        graph[2 * i].append((i + 2 * N, 0))
    if 2 * i + 1 < N:
        graph[2 * i + 1 + 2 * N].append((i + 2 * N, 0))
    else:
        graph[2 * i + 1].append((i + 2 * N, 0))
for _ in range(Q):
    query = map(int, readline().split())
    t = next(query)
    if t == 1:
        (v, u, w) = query
        v -= 1
        u -= 1
        graph[v + N].append((u + N, w))
    elif t == 2:
        (v, l, r, w) = query
        v -= 1
        l -= 1
        for u in ST.Interval_Decomp(l, r):
            graph[v + N].append((u, w))
    elif t == 3:
        (v, l, r, w) = query
        v -= 1
        l -= 1
        for u in ST.Interval_Decomp(l, r):
            if u < N:
                graph[u + 2 * N].append((v + N, w))
            else:
                graph[u].append((v + N, w))
inf = 1 << 60
G = Graph(3 * N, graph=graph, directed=True, weighted=True, inf=inf)
dist = G.Dijkstra(s + N)
ans_lst = dist[N:2 * N]
for i in range(N):
    if ans_lst[i] == inf:
        ans_lst[i] = -1
print(*ans_lst)

Solution (Python):
import pypyjit
pypyjit.set_param('max_unroll_recursion=-1')
from collections import *
from itertools import *
from functools import *
from heapq import *
import sys, math
input = sys.stdin.buffer.readline
(N, Q, S) = map(int, input().split())
n = 1
while n < N:
    n *= 2
N3 = 3 * n + 1
e = [[] for _ in range(N3 + 2 * Q)]
for i in range(n - 1, 0, -1):
    a = 2 * i
    b = 2 * i + 1
    e[i].append((a, 0))
    e[i].append((b, 0))
    if n <= a < 2 * n:
        e[a].append((i + 2 * n, 0))
    else:
        e[a + 2 * n].append((i + 2 * n, 0))
    if n <= b < 2 * n:
        e[b].append((i + 2 * n, 0))
    else:
        e[b + 2 * n].append((i + 2 * n, 0))
q = 0

def add(l1, r1, l2, r2, c):
    global q, e
    source = []
    l1 += n
    r1 += n
    while l1 < r1:
        if l1 & 1:
            if n <= l1 < 2 * n:
                source.append(l1)
            else:
                source.append(l1 + 2 * n)
            l1 += 1
        if r1 & 1:
            if n <= r1 - 1 < 2 * n:
                source.append(r1 - 1)
            else:
                source.append(r1 + 2 * n - 1)
        l1 >>= 1
        r1 >>= 1
    target = []
    l2 += n
    r2 += n
    while l2 < r2:
        if l2 & 1:
            target.append(l2)
            l2 += 1
        if r2 & 1:
            target.append(r2 - 1)
        l2 >>= 1
        r2 >>= 1
    for s in source:
        e[s].append((N3 + q, 0))
    for t in target:
        e[N3 + q + 1].append((t, 0))
    e[N3 + q].append((N3 + q + 1, c))
    q += 2
    return
S -= 1
INF = float('inf')

def dijkstra(s, e):
    N = len(e)
    dist = [INF] * N
    dist[s] = 0
    h = []
    heappush(h, (0, s))
    while h:
        (nw, v) = heappop(h)
        if dist[v] != nw:
            continue
        for (iv, ic) in e[v]:
            nc = ic + nw
            if nc < dist[iv]:
                dist[iv] = nc
                heappush(h, (nc, iv))
    return dist
for _ in range(Q):
    query = list(map(int, input().split()))
    if query[0] == 1:
        (v, u, w) = query[1:]
        v -= 1
        u -= 1
        add(v, v + 1, u, u + 1, w)
    elif query[0] == 2:
        (v, l, r, w) = query[1:]
        v -= 1
        l -= 1
        add(v, v + 1, l, r, w)
    else:
        (v, l, r, w) = query[1:]
        v -= 1
        l -= 1
        add(l, r, v, v + 1, w)
D = dijkstra(n + S, e)
ans = []
for i in range(N):
    if D[n + i] == INF:
        ans.append(-1)
    else:
        ans.append(D[n + i])
print(*ans)

Solution (Python):
from io import BytesIO, IOBase
import sys
import os
import bisect
import math
import random
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations, count, product
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase
from typing import *

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        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')
BUFSIZE = 5096

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

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

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda : sys.stdin.readline().rstrip('\r\n')

def I():
    return input()

def II():
    return int(input())

def MII():
    return map(int, input().split())

def LI():
    return list(input().split())

def LII():
    return list(map(int, input().split()))

def GMI():
    return map(lambda x: int(x) - 1, input().split())

def LGMI():
    return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')
(n, q, s) = MII()
s -= 1
path = [[] for _ in range(4 * n)]
for i in range(1, 2 * n):
    path[i].append((i // 2, 0))
    path[n * 2 + i // 2].append((n * 2 + i, 0))
for i in range(n, 2 * n):
    path[i + n * 2].append((i, 0))
    path[i].append((i + n * 2, 0))
for _ in range(q):
    query = LGMI()
    query[-1] += 1
    if query[0] == 0:
        (u, v, w) = query[1:]
        path[n + u].append((n + v, w))
    elif query[0] == 1:
        (u, l, r, w) = query[1:]
        (ql, qr) = (n + l, n + r + 1)
        while ql < qr:
            if ql & 1:
                path[u + 3 * n].append((ql + 2 * n, w))
                ql += 1
            if qr & 1:
                qr -= 1
                path[u + 3 * n].append((qr + 2 * n, w))
            ql //= 2
            qr //= 2
    else:
        (u, l, r, w) = query[1:]
        (ql, qr) = (n + l, n + r + 1)
        while ql != qr:
            if ql & 1:
                path[ql].append((u + n, w))
                ql += 1
            if qr & 1:
                qr -= 1
                path[qr].append((u + n, w))
            ql //= 2
            qr //= 2
dist = [inf] * (4 * n)
dist[s + 3 * n] = 0
hpq = [(0, s + 3 * n)]
while hpq:
    (d, u) = heappop(hpq)
    if dist[u] == d:
        for (v, w) in path[u]:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                heappush(hpq, (dist[v], v))
print(*(dist[i] if dist[i] < inf else -1 for i in range(3 * n, 4 * n)))