Moving Both Hands (Codeforces 1725M)
Tags: DP, shortest paths

Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $$$N$$$ vertices and $$$M$$$ edges. In the graph, edge $$$i$$$ connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. By using the $$$i$$$-th edge, something can move from $$$U_i$$$ to $$$V_i$$$, but not from $$$V_i$$$ to $$$U_i$$$.To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $$$U_i$$$ to vertex $$$V_i$$$, Pak Chanek needs a time of $$$W_i$$$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.Pak Chanek has several questions. For each $$$p$$$ satisfying $$$2 \leq p \leq N$$$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$p$$$, or report if it is impossible.

Input: The first line contains two integers $$$N$$$ and $$$M$$$ ($$$2 \leq N \leq 10^5$$$, $$$0 \leq M \leq 2 \cdot 10^5$$$) — the number of vertices and edges in the graph.The $$$i$$$-th of the next $$$M$$$ lines contains three integers $$$U_i$$$, $$$V_i$$$, and $$$W_i$$$ ($$$1 \le U_i, V_i \le N$$$, $$$U_i \neq V_i$$$, $$$1 \le W_i \le 10^9$$$) — a directed edge that connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. There is no pair of different edges $$$i$$$ and $$$j$$$ such that $$$U_i = U_j$$$ and $$$V_i = V_j$$$.

Output: Output a line containing $$$N-1$$$ integers. The $$$j$$$-th integer represents the minimum time in seconds needed by Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$j+1$$$, or $$$-1$$$ if it is impossible.

Note: If initially Pak Chanek's left hand is on vertex $$$1$$$ and his right hand is on vertex $$$5$$$, Pak Chanek can do the following moves:   Move his right hand to vertex $$$4$$$ in $$$1$$$ second.  Move his left hand to vertex $$$2$$$ in $$$2$$$ seconds.  Move his left hand to vertex $$$4$$$ in $$$1$$$ second. In total it needs $$$1+2+1=4$$$ seconds. It can be proven that there is no other way that is faster.

Sample Inputs:
5 7
1 2 2
2 4 1
4 1 4
2 5 3
5 4 1
5 2 4
2 1 1

Sample Outputs:
1 -1 3 4

Solution (Python):
import heapq

def main():
    (n, m) = readIntArr()
    adjforward = [[] for _ in range(n)]
    adjbackward = [[] for _ in range(n)]
    for __ in range(m):
        (u, v, w) = readIntArr()
        u -= 1
        v -= 1
        adjforward[u].append((v, w))
        adjbackward[v].append((u, w))
    inf = int(2e+18)
    dist = [inf] * n
    dist[0] = 0
    h = [0]
    while h:
        X = heapq.heappop(h)
        (d, u) = divmod(X, n)
        if dist[u] == d:
            for (v, w) in adjforward[u]:
                if d + w < dist[v]:
                    dist[v] = d + w
                    heapq.heappush(h, (d + w) * n + v)
    ans = [inf] * n
    ans[0] = 0
    h = []
    for u in range(1, n):
        if dist[u] != inf:
            ans[u] = dist[u]
            h.append(dist[u] * n + u)
    h.append(0)
    heapq.heapify(h)
    while h:
        X = heapq.heappop(h)
        (d, u) = divmod(X, n)
        if ans[u] == d:
            for (v, w) in adjbackward[u]:
                if d + w < ans[v]:
                    ans[v] = d + w
                    heapq.heappush(h, (d + w) * n + v)
    ans2 = []
    for u in range(1, n):
        if ans[u] == inf:
            ans2.append(-1)
        else:
            ans2.append(ans[u])
    oneLineArrayPrint(ans2)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b, c):
    print('? {} {} {}'.format(a, b, c))
    sys.stdout.flush()
    return int(input())

def answerInteractive(x1, x2):
    print('! {} {}'.format(x1, x2))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()

Solution (Python):
import heapq

def main():
    (n, m) = readIntArr()
    adjforward = [[] for _ in range(n)]
    adjbackward = [[] for _ in range(n)]
    for __ in range(m):
        (u, v, w) = readIntArr()
        u -= 1
        v -= 1
        adjforward[u].append((v, w))
        adjbackward[v].append((u, w))
    inf = int(2e+18)
    dist = [inf] * n
    dist[0] = 0
    h = [0]
    while h:
        X = heapq.heappop(h)
        (d, u) = divmod(X, n)
        if dist[u] == d:
            for (v, w) in adjforward[u]:
                if d + w < dist[v]:
                    dist[v] = d + w
                    heapq.heappush(h, (d + w) * n + v)
    ans = [inf] * n
    ans[0] = 0
    h = []
    for u in range(1, n):
        if dist[u] != inf:
            ans[u] = dist[u]
            h.append(dist[u] * n + u)
    h.append(0)
    heapq.heapify(h)
    while h:
        X = heapq.heappop(h)
        (d, u) = divmod(X, n)
        if ans[u] == d:
            for (v, w) in adjbackward[u]:
                if d + w < ans[v]:
                    ans[v] = d + w
                    heapq.heappush(h, (d + w) * n + v)
    ans2 = []
    for u in range(1, n):
        if ans[u] == inf:
            ans2.append(-1)
        else:
            ans2.append(ans[u])
    oneLineArrayPrint(ans2)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b, c):
    print('? {} {} {}'.format(a, b, c))
    sys.stdout.flush()
    return int(input())

def answerInteractive(x1, x2):
    print('! {} {}'.format(x1, x2))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()

Solution (Python):
import heapq

def main():
    (n, m) = readIntArr()
    adjforward = [[] for _ in range(n)]
    adjbackward = [[] for _ in range(n)]
    for __ in range(m):
        (u, v, w) = readIntArr()
        u -= 1
        v -= 1
        adjforward[u].append((v, w))
        adjbackward[v].append((u, w))
    inf = int(2e+18)
    dist = [inf] * n
    dist[0] = 0
    h = [(0, 0)]
    while h:
        (d, u) = heapq.heappop(h)
        if dist[u] == d:
            for (v, w) in adjforward[u]:
                if d + w < dist[v]:
                    dist[v] = d + w
                    heapq.heappush(h, (d + w, v))
    ans = [inf] * n
    ans[0] = 0
    h = []
    for u in range(1, n):
        if dist[u] != inf:
            ans[u] = dist[u]
            h.append((dist[u], u))
    h.append((0, 0))
    heapq.heapify(h)
    while h:
        (d, u) = heapq.heappop(h)
        if ans[u] == d:
            for (v, w) in adjbackward[u]:
                if d + w < ans[v]:
                    ans[v] = d + w
                    heapq.heappush(h, (d + w, v))
    ans2 = []
    for u in range(1, n):
        if ans[u] == inf:
            ans2.append(-1)
        else:
            ans2.append(ans[u])
    oneLineArrayPrint(ans2)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b, c):
    print('? {} {} {}'.format(a, b, c))
    sys.stdout.flush()
    return int(input())

def answerInteractive(x1, x2):
    print('! {} {}'.format(x1, x2))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()