Not Escaping (Codeforces 1627E)
Tags: Implement, shortest paths

Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i < c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.  

Input: The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases.The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively.The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$).The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i < c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it.It is guaranteed $$$a_i < c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building.The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.

Output: Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).

Note: The figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$:   Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &= 16. \end{align*} $$$$$$  Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &= 21. \end{align*} $$$$$$  Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).

Sample Inputs:
4
5 3 3
5 17 8 1 4
1 3 3 3 4
3 1 5 2 5
3 2 5 1 6
6 3 3
5 17 8 1 4 2
1 3 3 3 4
3 1 5 2 5
3 2 5 1 6
5 3 1
5 17 8 1 4
1 3 5 3 100
5 5 5
3 2 3 7 5
3 5 4 2 1
2 2 5 4 5
4 4 5 2 3
1 2 4 2 2
3 3 5 2 4

Sample Outputs:
16
NO ESCAPE
-90
27

Solution (Python):
from collections import Counter, defaultdict
from heapq import heappop, heappush
from sys import stdin, gettrace
if gettrace():

    def inputi():
        return input()
else:

    def input():
        return next(stdin)[:-1]

    def inputi():
        return stdin.buffer.readline()
INF = 1000000000000000000

def solve(n, m, k, xx, abcdh):
    lt = [set() for _ in range(n + 1)]
    ladders = [defaultdict(list) for _ in range(n + 1)]
    for (a, b, c, d, h) in abcdh:
        ladders[a][b].append((c, d, h))
    costs = [defaultdict(lambda : INF) for _ in range(n + 1)]
    costs[1][1] = 0
    lt[1].add(1)
    ladders[n][m].append((n, m, 0))
    for f in range(1, n + 1):
        if not lt[f]:
            continue
        fr = sorted(lt[f].union(ladders[f].keys()))
        pc = INF
        pr = 0
        for r in fr:
            if r in lt[f]:
                pc = costs[f][r] = min(costs[f][r], pc + (r - pr) * xx[f - 1])
                pr = r
            else:
                costs[f][r] = pc + (r - pr) * xx[f - 1]
        pc = INF
        pr = m + 1
        for r in fr[::-1]:
            if r in lt[f]:
                pc = costs[f][r] = min(costs[f][r], pc + (pr - r) * xx[f - 1])
                pr = r
            else:
                costs[f][r] = min(costs[f][r], pc + (pr - r) * xx[f - 1])
        for (b, cdh) in ladders[f].items():
            for (c, d, h) in cdh:
                lt[c].add(d)
                costs[c][d] = min(costs[c][d], costs[f][b] - h)
    if m not in costs[n]:
        return 'NO ESCAPE'
    else:
        return costs[n][m]

def main():
    t = int(input())
    for _ in range(t):
        (n, m, k) = map(int, input().split())
        xx = [int(a) for a in input().split()]
        abcdh = [[int(a) for a in input().split()] for _ in range(k)]
        print(solve(n, m, k, xx, abcdh))
if __name__ == '__main__':
    main()

Solution (Python):
from bisect import bisect_left
from heapq import heappop, heappush
from collections import defaultdict
import sys
input = sys.stdin.readline

def main():
    t = int(input())
    for _ in range(t):
        (n, m, k) = map(int, input().split())
        ladders = [[] for _ in range(n)]
        floors = [set() for _ in range(n)]
        x = list(map(int, input().split()))
        for _ in range(k):
            (a, b, c, d, h) = map(int, input().split())
            ladders[a - 1].append((b - 1, c - 1, d - 1, h))
            floors[a - 1].add(b - 1)
            floors[c - 1].add(d - 1)
        floors[0].add(0)
        floors[n - 1].add(m - 1)
        dist = defaultdict(lambda : float('inf'))
        dist[0, 0] = 0
        for (i, floor) in enumerate(floors):
            columns = sorted(list(floor))
            pq = []
            for col in columns:
                if dist[i, col] < float('inf'):
                    heappush(pq, (dist[i, col], col))
            while pq:
                (room_dist, room_col) = heappop(pq)
                idx = bisect_left(columns, room_col)
                if idx > 0:
                    n_dist = abs(columns[idx - 1] - columns[idx]) * x[i] + room_dist
                    if n_dist < dist[i, columns[idx - 1]]:
                        dist[i, columns[idx - 1]] = n_dist
                        pq.append((n_dist, columns[idx - 1]))
                if idx < len(columns) - 1:
                    n_dist = abs(columns[idx + 1] - columns[idx]) * x[i] + room_dist
                    if n_dist < dist[i, columns[idx + 1]]:
                        dist[i, columns[idx + 1]] = n_dist
                        pq.append((n_dist, columns[idx + 1]))
            for (b, c, d, h) in ladders[i]:
                dist[c, d] = min(dist[c, d], dist[i, b] - h)
        if dist[n - 1, m - 1] == float('inf'):
            print('NO ESCAPE')
        else:
            print(dist[n - 1, m - 1])
main()

Solution (Python):
from bisect import bisect_left
from heapq import heappop, heappush
from collections import defaultdict
import sys
input = sys.stdin.readline

def main():
    t = int(input())
    for _ in range(t):
        (n, m, k) = map(int, input().split())
        ladders = [[] for _ in range(n)]
        floors = [set() for _ in range(n)]
        x = list(map(int, input().split()))
        for _ in range(k):
            (a, b, c, d, h) = map(int, input().split())
            ladders[a - 1].append((b - 1, c - 1, d - 1, h))
            floors[a - 1].add(b - 1)
            floors[c - 1].add(d - 1)
        floors[0].add(0)
        floors[n - 1].add(m - 1)
        dist = defaultdict(lambda : float('inf'))
        dist[0, 0] = 0
        for (i, floor) in enumerate(floors):
            columns = sorted(list(floor))
            pq = []
            for col in columns:
                if dist[i, col] < float('inf'):
                    heappush(pq, (dist[i, col], col))
            while pq:
                (room_dist, room_col) = heappop(pq)
                idx = bisect_left(columns, room_col)
                if idx > 0:
                    n_dist = abs(columns[idx - 1] - columns[idx]) * x[i] + room_dist
                    if n_dist < dist[i, columns[idx - 1]]:
                        dist[i, columns[idx - 1]] = n_dist
                        pq.append((n_dist, columns[idx - 1]))
                if idx < len(columns) - 1:
                    n_dist = abs(columns[idx + 1] - columns[idx]) * x[i] + room_dist
                    if n_dist < dist[i, columns[idx + 1]]:
                        dist[i, columns[idx + 1]] = n_dist
                        pq.append((n_dist, columns[idx + 1]))
            for (b, c, d, h) in ladders[i]:
                dist[c, d] = min(dist[c, d], dist[i, b] - h)
        if dist[n - 1, m - 1] == float('inf'):
            print('NO ESCAPE')
        else:
            print(dist[n - 1, m - 1])
main()