Problem:


Score : 700 points

Problem Statement

We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki.

The i-th edge connects Vertex U_i and Vertex V_i.
The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki).

Takahashi departs Vertex S and Aoki departs Vertex T at the same time. Takahashi travels to Vertex T and Aoki travels to Vertex S, both in the shortest time possible.
Find the number of the pairs of ways for Takahashi and Aoki to choose their shortest paths such that they never meet (at a vertex or on an edge) during the travel, modulo 10^9 + 7.

Constraints

1 \leq N \leq 100 000

1 \leq M \leq 200 000

1 \leq S, T \leq N

S \neq T

1 \leq U_i, V_i \leq N (1 \leq i \leq M)

1 \leq D_i \leq 10^9 (1 \leq i \leq M)

If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).

U_i \neq V_i (1 \leq i \leq M)

D_i are integers.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
S T
U_1 V_1 D_1
U_2 V_2 D_2
:
U_M V_M D_M

Output

Print the answer.

Sample Input 1

4 4
1 3
1 2 1
2 3 1
3 4 1
4 1 1

Sample Output 1

2

There are two ways to choose shortest paths that satisfies the condition:

Takahashi chooses the path 1 \rightarrow 2 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 4 \rightarrow 1.

Takahashi chooses the path 1 \rightarrow 4 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 2 \rightarrow 1.

Sample Input 2

3 3
1 3
1 2 1
2 3 1
3 1 2

Sample Output 2

2

Sample Input 3

3 3
1 3
1 2 1
2 3 1
3 1 2

Sample Output 3

2

Sample Input 4

8 13
4 2
7 3 9
6 2 3
1 6 4
7 6 9
3 8 9
1 2 2
2 8 12
8 6 9
2 5 5
4 2 18
5 3 7
5 1 515371567
4 8 6

Sample Output 4

6



Sample input:
4 4
1 3
1 2 1
2 3 1
3 4 1
4 1 1


Sample output:
2

Submission status: Runtime Error

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

MOD, INF = 1000000007, float('inf')


def get_patterns_func(s, ancestors):
    cache = {s: 1}

    def get_patterns(v):
        if v in cache:
            return cache[v]
        return sum(get_patterns(a) for a in ancestors[v])

    return get_patterns


def solve(s, t, links):
    q = [(0, 0, s, -1, 0), (0, 0, t, -1, 1)]
    visited_fwd, visited_bwd = [INF] * n, [INF] * n
    ancestors_fwd, ancestors_bwd = defaultdict(set), defaultdict(set)
    collision_nodes, collision_links = set(), set()
    limit = 0
    while q:
        cost, cost_a, v, a, is_bwd = heappop(q)
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
            ancestors_self = ancestors_bwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd
            ancestors_self = ancestors_fwd

        relax_flag = False
        cost_preceding = visited_self[v]
        if cost_preceding == INF:
            visited_self[v] = cost
            relax_flag = True
        elif cost > cost_preceding:
            continue

        ancestors_self[v].add(a)

        cost_opp = visited_opp[v]
        if cost_opp != INF:
            limit = cost + cost_opp
            if cost == cost_opp:
                collision_nodes.add(v)
            else:
                collision_links.add((v, a) if is_bwd else (a, v))
            break

        if relax_flag:
            for u, du in links[v].items():
                nc = cost + du
                if visited_self[u] < nc:
                    continue
                heappush(q, (nc, cost, u, v, is_bwd))

    collision_time = limit / 2
    while q:
        cost, cost_a, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited_bwd if is_bwd else visited_fwd
        if visited_self[v] == INF:
            visited_self[v] = cost
        if is_bwd:
            if cost == collision_time:
                ancestors_bwd[v].add(a)
            continue
        if cost_a == collision_time:
            collision_nodes.add(a)
        elif cost == collision_time:
            collision_nodes.add(v)
            ancestors_fwd[v].add(a)
        else:
            collision_links.add((a, v))

    patterns_fwd = get_patterns_func(s, ancestors_fwd)
    patterns_bwd = get_patterns_func(t, ancestors_bwd)
    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        if visited_fwd[v] == visited_bwd[v]:
            r = patterns_fwd(v) * patterns_bwd(v)
            shortest_count += r
            shortest_count %= MOD
            collision_count += r * r
            collision_count %= MOD

    for u, v in collision_links:
        if visited_fwd[u] + visited_bwd[v] + links[u][v] == limit:
            r = patterns_fwd(u) * patterns_bwd(v)
            shortest_count += r
            shortest_count %= MOD
            collision_count += r * r
            collision_count %= MOD

    return (shortest_count ** 2 - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [{} for _ in range(n)]
for uvd in sys.stdin.readlines():
    u, v, d = map(int, uvd.split())
    # for _ in range(m):
    #     u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u][v] = d
    links[v][u] = d
print(solve(s, t, links))

Submission status: Runtime Error

Solution code:
from sys import exit, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect
from heapq import heappush, heappop

def read():
  return int(input())

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

INF = 10**16
MOD = 10**9 + 7

(N, M) = reads()
(S, T) = reads()
(S, T) = (S-1, T-1)

edges = [[] for _ in range(N)]
for _ in range(M):
    (U, V, D) = reads()
    (U, V) = (U-1, V-1)
    edges[U].append((D, V))
    edges[V].append((D, U))

def dijkstra(s):
    que = [(0, s)]
    ds = [INF] * N; ds[s] = 0

    while que:
        (D, v) = heappop(que)
        if ds[v] < D:
            continue
        for (d, w) in edges[v]:
            if ds[w] > ds[v] + d:
                ds[w] = ds[v] + d
                heappush(que, (ds[w], w))
    return ds

def counting(s, ds):
    ns = [0] * N; ns[s] = 1
    visited = [False] * N
    
    def walk(i):
        if visited[i]:
            return
        visited[i] = True
        for (d, w) in edges[i]:
            if ds[w] - ds[i] == d:
                ns[w] = (ns[w] + ns[i]) % MOD
                walk(w)

    walk(s)
    return ns

dS = dijkstra(S)
nS = counting(S, dS)

dT = dijkstra(T)
nT = counting(T, dT)

dtot = dS[T]
ans = (nS[T] * nT[S]) % MOD

for i in range(N):
    if dS[i] == dT[i] and dS[i] + dT[i] == dtot:
        ans = (ans - pow(nS[i] * nT[i], 2, MOD)) % MOD

egen = ((i, j, d) for i in range(N) for (d, j) in edges[i] if i < j)
for i, j, d in egen:
    if dS[i] + d + dT[j] == dtot and abs(dT[j] - dS[i]) < d:
        ans = (ans - pow(nS[i] * nT[j], 2 , MOD)) % MOD

print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
import sys
sys.setrecursionlimit(300000)


def dfs(x, ls, rs, pos):
    xpos = 0 if pos[x] is None else pos[x]
    for r, d in ls.get(x, []):
        if pos[r] is not None:
            if pos[r] - xpos != d:
                return False
        else:
            pos[r] = xpos + d
            if not dfs(r, ls, rs, pos):
                return False
    for l, d in rs.get(x, []):
        if pos[l] is not None:
            if xpos - pos[l] != d:
                return False
        else:
            pos[l] = xpos - d
            if not dfs(l, ls, rs, pos):
                return False
    return True


def main():
    n, m = list(map(int, input().split()))
    pos = [None for _ in range(n + 1)]

    ls = {}
    rs = {}
    for _ in range(m):
        l, r, d = list(map(int, input().split()))
        lsl = ls.get(l, [])
        lsl.append((r, d))
        ls[l] = lsl
        rsr = rs.get(r, [])
        rsr.append((l, d))
        rs[r] = rsr

    for i in range(n):
        if not dfs(i+1, ls, rs, pos):
            print('No')
            return

    pos = list(filter(lambda x: x is not None, pos))
    if len(pos) > 0:
        L, R = min(pos), max(pos)
        if R - L > 1e9:
            print('No')
            return

    print('Yes')


if __name__ == '__main__':
    main()