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:
import sys
input = sys.stdin.readline

INF = 10**18
mod = 10**9+7
# AOJ GRL_1_A Single Sourse Shortest Path
import heapq as hp

N, M = map(int, input().split())
s, t = map(int, input().split())
s -= 1; t -= 1
graph = [[] for _ in range(N)]
for _ in range(M):
    n, m, d = map(int, input().split())
    graph[n-1].append((d, m-1)) 
    graph[m-1].append((d, n-1)) #無向グラフならこれ使う

def dijkstra(s):
    D = [INF for _ in range(N)] # 頂点iへの最短距離がD[i]
    B = [0]*N
    D[s] = 0
    B[s] = 1
    q = [] # しまっていく優先度付きキュー
    hp.heappush(q, (0, s))

    while q:
        nd, np = hp.heappop(q)
        if D[np] < nd:
            continue
        for d, p in graph[np]:
            if D[p] > D[np] + d:
                D[p] = D[np] + d
                B[p] = B[np]
                hp.heappush(q, (D[p], p))
            elif D[p] == D[np] + d:
                B[p] = (B[p] + B[np])%mod
    return D, B

sD, sB = dijkstra(s)
tD, tB = dijkstra(t)

distance = sD[t]

ans = 0
for n in range(N):
    for d, m in graph[n]:
        if sD[n] + d + tD[m] == distance and 2*sD[n] < distance < 2*(sD[n]+d):
            ans = (ans + (sB[n]*tB[m])**2)%mod
    if sD[n] + tD[n] == distance and 2*sD[n] == distance:
        ans = (ans + (sB[n]*tB[n])**2) % mod
ans = (sB[t]*tB[s] - ans) % mod
print(ans)
//...

Submission status: Runtime Error

Solution code:
import sys
from collections import deque, defaultdict
import heapq
input = sys.stdin.buffer.readline


def dijkstra(adj, start):
    # adj: [[to, cost] * vertices], 0th index must be empty
    dist = [float('inf')] * len(adj)
    dist[start] = 0
    q = []
    heapq.heappush(q, (0, start))
    while q:
        min_dist, v_from = heapq.heappop(q)
        if min_dist > dist[v_from]:
            continue
        v_tos = adj[v_from]
        for v_to, cost in v_tos:
            if min_dist + cost < dist[v_to]:
                dist[v_to] = min_dist + cost
                heapq.heappush(q, (dist[v_to], v_to))
    return dist


def main():
    mod = 10**9+7
    N, M = map(int, input().split())
    s, t = map(int, input().split())
    adj = [[] for _ in range(N+1)]
    for _ in range(M):
        l, r, d = map(int, input().split())
        adj[l].append((r, d))
        adj[r].append((l, d))

    dist = dijkstra(adj, s)
    collision_T = dist[t] / 2 if dist[t] % 2 == 1 else dist[t] // 2
    route = [0] * (N+1)
    route[t] = 1
    que = []
    heapq.heappush(que, (-dist[t], t))
    col_edge = []
    seen = [0] * (N+1)
    seen[t] = 1
    seen_col_edge = defaultdict(int)
    while que:
        _, v = heapq.heappop(que)
        for u, d in adj[v]:
            if dist[v] == dist[u] + d:
                route[u] = (route[u] + route[v]) % mod
                if dist[u] < collision_T < dist[v]:
                    assert seen_col_edge[(u, v)] == 0
                    seen_col_edge[(u, v)] = 1
                    col_edge.append((u, v))
                elif dist[v] == collision_T:
                    assert seen_col_edge[(v, v)] == 0
                    seen_col_edge[(v, v)] = 1
                    col_edge.append((v, v))
                if not seen[u]:
                    heapq.heappush(que, (-dist[u], u))
                    seen[u] = 1

    #reverse
    route2 = [0] * (N+1)
    route2[s] = 1
    que = []
    heapq.heappush(que, (0, s))
    seen = [0] * (N+1)
    seen[s] = 1
    while que:
        _, v = heapq.heappop(que)
        for u, d in adj[v]:
            if dist[u] == dist[v] + d:
                route2[u] = (route2[u] + route2[v]) % mod
                if not seen[u]:
                    heapq.heappush(que, (dist[u], u))
                    seen[u] = 1

    #print(route)
    #print(route2)

    ans = pow(route[s], 2, mod)
    for u, v in col_edge:
        tmp = (route[v] * route2[u])%mod
        ans = (ans - pow(tmp, 2, mod))%mod
    print(ans)


if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque, defaultdict
import heapq
input = sys.stdin.buffer.readline


def dijkstra(adj, start):
    # adj: [[to, cost] * vertices], 0th index must be empty
    dist = [float('inf')] * len(adj)
    dist[start] = 0
    q = []
    heapq.heappush(q, (0, start))
    while q:
        min_dist, v_from = heapq.heappop(q)
        if min_dist > dist[v_from]:
            continue
        v_tos = adj[v_from]
        for v_to, cost in v_tos:
            if min_dist + cost < dist[v_to]:
                dist[v_to] = min_dist + cost
                heapq.heappush(q, (dist[v_to], v_to))
    return dist

def main():
    mod = 10**9+7
    N, M = map(int, input().split())
    s, t = map(int, input().split())
    adj = [[] for _ in range(N+1)]
    for _ in range(M):
        l, r, d = map(int, input().split())
        adj[l].append((r, d))
        adj[r].append((l, d))

    dist = dijkstra(adj, s)
    T = dist[t]
    collision_T = T / 2
    route = [0] * (N+1)
    route[t] = 1
    que = deque()
    que.append(t)
    col_edge = []
    seen = [0] * (N+1)
    seen[t] = 1
    while que:
        v = que.popleft()
        for u, d in adj[v]:
            if dist[v] == dist[u] + d:
                route[u] = (route[u] + route[v]) % mod
                if dist[u] < collision_T < dist[v]:
                    col_edge.append((u, v))
                elif dist[u] == collision_T:
                    col_edge.append((u, u))
                if not seen[u]:
                    que.append(u)
                    seen[u] = 1

    #reverse
    route2 = [0] * (N+1)
    route2[s] = 1
    que = deque()
    que.append(s)
    seen = [0] * (N+1)
    seen[s] = 1
    while que:
        v = que.popleft()
        for u, d in adj[v]:
            if dist[u] == dist[v] + d:
                route2[u] = (route2[u] + route2[v]) % mod
                if not seen[u]:
                    que.append(u)
                    seen[u] = 1

    if route[s] != route2[t]:
        assert False

    ans = pow(route[s], 2, mod)
    for u, v in col_edge:
        tmp = (route[v] * route2[u])%mod
        ans = (ans - pow(tmp, 2, mod))%mod
    print(ans)


if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline

from heapq import heappop as hpp, heappush as hp
def dijkstra(N, s, Edge):
    geta = 64
    inf = 1<<geta
    dist = [inf] * N
    dist[s] = 0
    Q = [s]
    dp = [0]*N
    dp[s] = 1
    while Q:
        k = hpp(Q)
        dn = k>>geta
        vn = k^(dn<<geta)
        if dn > dist[vn]:
            continue
        for k in Edge[vn]:
            df = k>>geta
            vf = k^(df<<geta)
            if dist[vn] + df < dist[vf]:
                dist[vf] = dist[vn] + df
                dp[vf] = dp[vn]
                hp(Q, ((dn + df)<<geta)+vf)
            elif dist[vn] + df == dist[vf]:
                dp[vf] = (dp[vf] + dp[vn]) % MOD
    return dist, dp

MOD = 10**9+7
N, M = map(int, readline().split())
S, T = map(int, readline().split())
S -= 1
T -= 1

geta = 32
Edge = [[] for _ in range(N)]
for _ in range(M):
    u, v, d = map(int, readline().split())
    u -= 1
    v -= 1
    Edge[u].append(d<<geta|v)
    Edge[v].append(d<<geta|u)
    

dists, dps = dijkstra(N, S, Edge)
distt, dpt = dijkstra(N, T, Edge)
st = dists[T]

onpath = [i for i in range(N) if dists[i] + distt[i] == st]

ans = dps[T]**2%MOD
for i in onpath:
    if 2*dists[i] == 2*distt[i] == st:
        ans = (ans - pow(dps[i]*dpt[i], 2, MOD))%MOD
    
    for k in Edge[i]:
        cost = k>>geta
        vf = k^(cost<<geta)
        if dists[i] + cost + distt[vf] == st:
            if 2*dists[i] < st < 2*dists[vf]:
                ans = (ans - pow(dps[i]*dpt[vf], 2, MOD))%MOD
print(ans)

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline

from heapq import heappop as hpp, heappush as hp
def dijkstra(N, s, Edge):
    geta = 32
    inf = 1<<geta
    dist = [inf] * N
    dist[s] = 0
    Q = [s]
    dp = [0]*N
    dp[s] = 1
    while Q:
        k = hpp(Q)
        dn = k>>geta
        vn = k^(dn<<geta)
        if dn > dist[vn]:
            continue
        for k in Edge[vn]:
            df = k>>geta
            vf = k^(df<<geta)
            if dist[vn] + df < dist[vf]:
                dist[vf] = dist[vn] + df
                dp[vf] = dp[vn]
                hp(Q, ((dn + df)<<geta)+vf)
            elif dist[vn] + df == dist[vf]:
                dp[vf] = (dp[vf] + dp[vn]) % MOD
    return dist, dp

MOD = 10**9+7
N, M = map(int, readline().split())
S, T = map(int, readline().split())
S -= 1
T -= 1

geta = 32
Edge = [[] for _ in range(N)]
for _ in range(M):
    u, v, d = map(int, readline().split())
    u -= 1
    v -= 1
    Edge[u].append(d<<geta|v)
    Edge[v].append(d<<geta|u)
    

dists, dps = dijkstra(N, S, Edge)
distt, dpt = dijkstra(N, T, Edge)
st = dists[T]

onpath = [i for i in range(N) if dists[i] + distt[i] == st]

ans = dps[T]**2%MOD
for i in onpath:
    if 2*dists[i] == 2*ditt[i] == st:
        ans = (ans - pow(dps[i]*dpt[i], 2, MOD))%MOD
    
    for k in Edge[i]:
        cost = k>>geta
        vf = k^(cost<<geta)
        if dists[i] + cost + distt[vf] == st:
            if 2*dists[i] < st < 2*dists[vf]:
                ans = (ans - pow(dps[i]*dpt[vf], 2, MOD))%MOD
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from heapq import heappop, heappush
mod = 10**9+7
INF = 1<<60
N, M = map(int, input().split())
S, T = map(int, input().split())
E = [[] for _ in range(N+1)]
edges = []
for _ in range(M):
    u, v, d = map(int, input().split())
    E[u].append((v, d))
    E[v].append((u, d))
    edges.append((u, v, d))

def dijksrtra(start):
    Dist = [INF] * (N+1)
    Dist[start] = 0
    q = [(0, start)]
    while q:
        dist, v = heappop(q)
        if Dist[v] != dist:
            continue
        for u, d in E[v]:
            new_dist = dist + d
            if Dist[u] > new_dist:
                Dist[u] = new_dist
                heappush(q, (new_dist, u))
    return Dist

Dist_S = dijksrtra(S)
Dist_T = dijksrtra(T)
dist_st = Dist_S[T]

DAG_edges = []  # S -> T
DAG = [[] for _ in range(N+1)]
DAG_rev = [[] for _ in range(N+1)]
for u, v, d in edges:
    if Dist_S[u] + Dist_T[v] + d == dist_st:
        DAG_edges.append((u, v, d))
        DAG[u].append((v, d))
        DAG_rev[v].append((u, d))
    elif Dist_T[u] + Dist_S[v] + d == dist_st:
        DAG_edges.append((v, u, d))
        DAG[v].append((u, d))
        DAG_rev[u].append((v, d))

n_paths_S = [-1] * (N+1)
n_paths_T = [-1] * (N+1)
n_paths_S[S] = 1
n_paths_T[T] = 1
def calc_n_paths_S(v):
    if n_paths_S[v] != -1:
        return n_paths_S[v]
    res = 0
    for u, _ in DAG_rev[v]:
        res = (res + calc_n_paths_S(u)) % mod
    n_paths_S[v] = res
    return res
def calc_n_paths_T(v):
    if n_paths_T[v] != -1:
        return n_paths_T[v]
    res = 0
    for u, _ in DAG[v]:
        res = (res + calc_n_paths_T(u)) % mod
    n_paths_T[v] = res
    return res

ans = calc_n_paths_S(T)  # 全経路数
calc_n_paths_T(S)
#assert ans == calc_n_paths_T(S), (n_paths_S, n_paths_T)

ans = ans * ans % mod

for v, u, _ in DAG_edges:  # 辺ですれ違う場合
    if Dist_S[v]*2 < dist_st and dist_st < Dist_S[u]*2:
        ans = (ans - (n_paths_S[v]*n_paths_T[u])**2) % mod

# 頂点ですれ違う場合
for v, (dist, ns, nt) in enumerate(zip(Dist_S, n_paths_S, n_paths_T)):
    if dist*2 == dist_st:
        ans = (ans - (ns*nt)**2) % mod

print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from heapq import heappop, heappush
mod = 10**9+7
INF = 1<<60
N, M = map(int, input().split())
S, T = map(int, input().split())
E = [[] for _ in range(N+1)]
edges = []
for _ in range(M):
    u, v, d = map(int, input().split())
    E[u].append((v, d))
    E[v].append((u, d))
    edges.append((u, v, d))

def dijksrtra(start):
    Dist = [INF] * (N+1)
    Dist[start] = 0
    q = [(0, start)]
    while q:
        dist, v = heappop(q)
        if Dist[v] != dist:
            continue
        for u, d in E[v]:
            new_dist = dist + d
            if Dist[u] > new_dist:
                Dist[u] = new_dist
                heappush(q, (new_dist, u))
    return Dist

Dist_S = dijksrtra(S)
Dist_T = dijksrtra(T)
dist_st = Dist_S[T]

DAG_edges = []  # S -> T
DAG = [[] for _ in range(N+1)]
DAG_rev = [[] for _ in range(N+1)]
for u, v, d in edges:
    if Dist_S[u] + Dist_T[v] + d == dist_st:
        DAG_edges.append((u, v, d))
        DAG[u].append((v, d))
        DAG_rev[v].append((u, d))
    elif Dist_T[u] + Dist_S[v] + d == dist_st:
        DAG_edges.append((v, u, d))
        DAG[v].append((u, d))
        DAG_rev[u].append((v, d))

n_paths_S = [-1] * (N+1)
n_paths_T = [-1] * (N+1)
n_paths_S[S] = 1
n_paths_T[T] = 1
def calc_n_paths_S(v):
    if n_paths_S[v] != -1:
        return n_paths_S[v]
    res = 0
    for u, _ in DAG_rev[v]:
        res = (res + calc_n_paths_S(u)) % mod
    n_paths_S[v] = res
    return res
def calc_n_paths_T(v):
    if n_paths_T[v] != -1:
        return n_paths_T[v]
    res = 0
    for u, _ in DAG[v]:
        res = (res + calc_n_paths_T(u)) % mod
    n_paths_T[v] = res
    return res

ans = calc_n_paths_S(T)  # 全経路数
assert ans == calc_n_paths_T(S), (n_paths_S, n_paths_T)

ans = ans * ans % mod

for v, u, _ in DAG_edges:  # 辺ですれ違う場合
    if Dist_S[v]*2 < dist_st and dist_st < Dist_S[u]*2:
        ans = (ans - (n_paths_S[v]*n_paths_T[u])**2) % mod

# 頂点ですれ違う場合
for v, (dist, ns, nt) in enumerate(zip(Dist_S, n_paths_S, n_paths_T)):
    if dist*2 == dist_st:
        ans = (ans - (ns*nt)**2) % mod

print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from heapq import heappop, heappush
mod = 10**9+7
INF = 1<<60
N, M = map(int, input().split())
S, T = map(int, input().split())
E = [[] for _ in range(N+1)]
edges = []
for _ in range(M):
    u, v, d = map(int, input().split())
    E[u].append((v, d))
    E[v].append((u, d))
    edges.append((u, v, d))

def dijksrtra(start):
    Dist = [INF] * (N+1)
    Dist[start] = 0
    q = [(0, start)]
    while q:
        dist, v = heappop(q)
        if Dist[v] != dist:
            continue
        for u, d in E[v]:
            new_dist = dist + d
            if Dist[u] > new_dist:
                Dist[u] = new_dist
                heappush(q, (new_dist, u))
    return Dist

Dist_S = dijksrtra(S)
Dist_T = dijksrtra(T)
dist_st = Dist_S[T]

DAG_edges = []  # S -> T
DAG = [[] for _ in range(N+1)]
DAG_rev = [[] for _ in range(N+1)]
for u, v, d in edges:
    if Dist_S[u] + Dist_T[v] + d == dist_st:
        DAG_edges.append((u, v, d))
        DAG[u].append((v, d))
        DAG_rev[v].append((u, d))
    elif Dist_T[u] + Dist_S[v] + d == dist_st:
        DAG_edges.append((v, u, d))
        DAG[v].append((u, d))
        DAG_rev[u].append((v, d))

n_paths_S = [-1] * (N+1)
n_paths_T = [-1] * (N+1)
n_paths_S[S] = 1
n_paths_T[T] = 1
def calc_n_paths_S(v):
    if n_paths_S[v] != -1:
        return n_paths_S[v]
    res = 0
    for u, _ in DAG_rev[v]:
        res = (res + calc_n_paths_S(u)) % mod
    n_paths_S[v] = res
    return res
def calc_n_paths_T(v):
    if n_paths_T[v] != -1:
        return n_paths_T[v]
    res = 0
    for u, _ in DAG[v]:
        res = (res + calc_n_paths_T(u)) % mod
    n_paths_T[v] = res
    return res

ans = calc_n_paths_S(T)  # 全経路数
assert ans == calc_n_paths_T(S), (n_paths_S, n_paths_T)

ans = ans * ans % mod

half = dist_st / 2.0
assert half * 2 == dist_st
for v, u, _ in DAG_edges:  # 辺ですれ違う場合
    if Dist_S[v] < half and half < Dist_S[u]:
        ans = (ans - (n_paths_S[v]*n_paths_T[u])**2) % mod

# 頂点ですれ違う場合
for v, (dist, ns, nt) in enumerate(zip(Dist_S, n_paths_S, n_paths_T)):
    if dist == half:
        ans = (ans - (ns*nt)**2) % mod

print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush
mod = 10**9+7
N, M = map(int, input().split())
S, T = map(int, input().split())
E = [[] for _ in range(N+1)]
edges = []
for _ in range(M):
    u, v, d = map(int, input().split())
    E[u].append((v, d))
    E[v].append((u, d))
    edges.append((u, v, d))

def dijksrtra(start):
    Dist = [float("inf")] * (N+1)
    Dist[start] = 0
    q = [(0, start)]
    while q:
        dist, v = heappop(q)
        if Dist[v] != dist:
            continue
        for u, d in E[v]:
            new_dist = dist + d
            if Dist[u] > new_dist:
                Dist[u] = new_dist
                heappush(q, (new_dist, u))
    return Dist

Dist_S = dijksrtra(S)
Dist_T = dijksrtra(T)
dist_st = Dist_S[T]

DAG_edges = []  # S -> T
DAG = [[] for _ in range(N+1)]
DAG_rev = [[] for _ in range(N+1)]
for u, v, d in edges:
    if Dist_S[u] + Dist_T[v] + d == dist_st:
        DAG_edges.append((u, v, d))
        DAG[u].append((v, d))
        DAG_rev[v].append((u, d))
    elif Dist_T[u] + Dist_S[v] + d == dist_st:
        DAG_edges.append((v, u, d))
        DAG[v].append((u, d))
        DAG_rev[u].append((v, d))

n_paths_S = [-1] * (N+1)
n_paths_T = [-1] * (N+1)
n_paths_S[S] = 1
n_paths_T[T] = 1
def calc_n_paths_S(v):
    if n_paths_S[v] != -1:
        return n_paths_S[v]
    res = 0
    for u, _ in DAG_rev[v]:
        res = (res + calc_n_paths_S(u)) % mod
    n_paths_S[v] = res
    return res
def calc_n_paths_T(v):
    if n_paths_T[v] != -1:
        return n_paths_T[v]
    res = 0
    for u, _ in DAG[v]:
        res = (res + calc_n_paths_T(u)) % mod
    n_paths_T[v] = res
    return res

ans = calc_n_paths_S(T)  # 全経路数
assert ans == calc_n_paths_T(S), (n_paths_S, n_paths_T)

ans = ans * ans % mod

half = dist_st / 2.0
assert half * 2 == dist_st
for v, u, _ in DAG_edges:  # 辺ですれ違う場合
    if Dist_S[v] < half and half < Dist_S[u]:
        ans = (ans - (n_paths_S[v]*n_paths_T[u])**2) % mod

# 頂点ですれ違う場合
for v, (dist, ns, nt) in enumerate(zip(Dist_S, n_paths_S, n_paths_T)):
    if dist == half:
        ans = (ans - (ns*nt)**2) % mod

print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush
mod = 10**9+7
N, M = map(int, input().split())
S, T = map(int, input().split())
E = [[] for _ in range(N+1)]
edges = []
for _ in range(M):
    u, v, d = map(int, input().split())
    E[u].append((v, d))
    E[v].append((u, d))
    edges.append((u, v, d))

def dijksrtra(start):
    Dist = [float("inf")] * (N+1)
    Dist[start] = 0
    q = [(0, start)]
    while q:
        dist, v = heappop(q)
        if Dist[v] != dist:
            continue
        for u, d in E[v]:
            new_dist = dist + d
            if Dist[u] > new_dist:
                Dist[u] = new_dist
                heappush(q, (new_dist, u))
    return Dist

Dist_S = dijksrtra(S)
Dist_T = dijksrtra(T)
dist_st = Dist_S[T]

DAG_edges = []  # S -> T
DAG = [[] for _ in range(N+1)]
DAG_rev = [[] for _ in range(N+1)]
for u, v, d in edges:
    if Dist_S[u] + Dist_T[v] + d == dist_st:
        DAG_edges.append((u, v, d))
        DAG[u].append((v, d))
        DAG_rev[v].append((u, d))
    elif Dist_T[u] + Dist_S[v] + d == dist_st:
        DAG_edges.append((v, u, d))
        DAG[v].append((u, d))
        DAG_rev[u].append((v, d))

n_paths_S = [-1] * (N+1)
n_paths_T = [-1] * (N+1)
n_paths_S[S] = 1
n_paths_T[T] = 1
def calc_n_paths_S(v):
    if n_paths_S[v] != -1:
        return n_paths_S[v]
    res = 0
    for u, _ in DAG_rev[v]:
        res = (res + calc_n_paths_S(u)) % mod
    n_paths_S[v] = res
    return res
def calc_n_paths_T(v):
    if n_paths_T[v] != -1:
        return n_paths_T[v]
    res = 0
    for u, _ in DAG[v]:
        res = (res + calc_n_paths_T(u)) % mod
    n_paths_T[v] = res
    return res

ans = calc_n_paths_S(T)  # 全経路数
assert ans == calc_n_paths_T(S), (n_paths_S, n_paths_T)

ans = ans * ans % mod

half = dist_st / 2.0
assert half * 2 == dist_st
for v, u, _ in DAG_edges:  # 辺ですれ違う場合
    if Dist_S[v] < half and half < Dist_S[u]:
        ans = (ans - (n_paths_S[v]*n_paths_T[u])**2) % mod

for v, (dist, ns, nt) in enumerate(zip(Dist_S, n_paths_S, n_paths_T)):
    # 頂点ですれ違う場合
    if dist == half:
        ans = (ans - (ns*nt)**2) % mod

print(ans)

Submission status: Runtime Error

Solution code:
# 参考: https://qiita.com/y-tsutsu/items/aa7e8e809d6ac167d6a1

from heapq import heappush, heappop
from typing import List, Tuple

# 多次元配列
# dp = [[0] * 3 for _ in range(5)


INF = 1 << 28
MOD = int(1e9) + 7


def dijkstra(graph: List[List[Tuple[int, int]]], s: int, t: int):
    n = len(graph)
    dist = [INF for _ in range(n)]
    cnts = [0 for _ in range(n)]

    pq = []
    heappush(pq, (0, s))
    dist[s] = 0
    cnts[s] = 1

    while pq:
        (cost, cur) = heappop(pq)

        if dist[cur] != cost:
            continue

        if cur == t:
            return dist, cnts

        for next_idx, next_cost in graph[cur]:
            if dist[next_idx] > cost + next_cost:
                heappush(pq, (cost + next_cost, next_idx))
                dist[next_idx] = cost + next_cost
                cnts[next_idx] = cnts[cur]
            elif dist[next_idx] == cost + next_cost:
                cnts[next_idx] = (cnts[next_idx] + cnts[cur]) % MOD

    return dist, cnts


# 入力を受け取る
n, m = map(int, input().split())

s, t = map(lambda i: int(i) - 1, input().split())

g = [[] for _ in range(n)]

es = [list(map(int, input().split())) for _ in range(m)]

for e in es:
    u, v, d = e
    g[u - 1].append((v - 1, d))
    g[v - 1].append((u - 1, d))

dst1, cnt1 = dijkstra(g, s, t)
dst2, cnt2 = dijkstra(g, t, s)

ret = cnt1[t] * cnt1[t] % MOD

for i in range(n):
    if 2 * dst1[i] == dst1[t]:
        sub = cnt1[i] * cnt2[i] % MOD
        sub = sub ** 2 % MOD
        ret = (ret + MOD - sub) % MOD

sum_sub = 0

for e in es:
    u, v, d = e
    u -= 1
    v -= 1

    if cnt1[u] > cnt1[v]:
        v, u = u, v

    if 2 * dst1[u] < dst1[t] < 2 * dst1[v] and dst1[u] + d + dst2[v] == dst1[t]:
        sub = cnt1[u] * cnt2[v] % MOD
        sub = sub ** 2 % MOD
        ret = (ret + MOD - sub) % MOD

print(ret)

Submission status: Runtime Error

Solution code:
# 参考: https://qiita.com/y-tsutsu/items/aa7e8e809d6ac167d6a1

from heapq import heappush, heappop


# 多次元配列
# dp = [[0] * 3 for _ in range(5)


class Edge:
    def __init__(self, to: int, cost: int):
        self._to = to
        self._cost = cost

    @property
    def to(self):
        return self._to

    @property
    def cost(self):
        return self._cost


class Edges(list):
    def __init__(self):
        list.__init__(self)


INF = 1 << 28
MOD = int(1e9) + 7


def dijkstra(graph, s: int, t: int):
    n = len(graph)
    dist = [INF for _ in range(n)]
    cnts = [0 for _ in range(n)]

    pq = []
    heappush(pq, (0, s))
    dist[s] = 0
    cnts[s] = 1

    while pq:
        (cost, cur) = heappop(pq)

        if dist[cur] != cost:
            continue
        
        if cur == t:
            return dist, cnts

        for next in graph[cur]:
            if dist[next.to] > cost + next.cost:
                heappush(pq, (cost + next.cost, next.to))
                dist[next.to] = cost + next.cost
                cnts[next.to] = cnts[cur]
            elif dist[next.to] == cost + next.cost:
                cnts[next.to] = (cnts[next.to] + cnts[cur]) % MOD

    return dist, cnts


# 入力を受け取る
n, m = map(int, input().split())

s, t = map(lambda i: int(i) - 1, input().split())

g = [Edges() for _ in range(n)]

es = [list(map(int, input().split())) for _ in range(m)]

for e in es:
    u, v, d = e
    g[u - 1].append(Edge(v - 1, d))
    g[v - 1].append(Edge(u - 1, d))

dst1, cnt1 = dijkstra(g, s)
dst2, cnt2 = dijkstra(g, t)

ret = cnt1[t] * cnt1[t] % MOD

for i in range(n):
    if 2 * dst1[i] == dst1[t]:
        sub = cnt1[i] * cnt2[i] % MOD
        sub = sub ** 2 % MOD
        ret = (ret + MOD - sub) % MOD

sum_sub = 0

for e in es:
    u, v, d = e
    u -= 1
    v -= 1

    if cnt1[u] > cnt1[v]:
        v, u = u, v

    if 2 * dst1[u] < dst1[t] < 2 * dst1[v] and dst1[u] + d + dst2[v] == dst1[t]:
        sub = cnt1[u] * cnt2[v] % MOD
        sub = sub ** 2 % MOD
        ret = (ret + MOD - sub) % MOD

print(ret)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
MOD = 10**9 + 7

def dijkstra(g, v_size, st):
    """Dijkstra method"""

    d = [float('inf')] * v_size
    d[st] = 0

    que = [(0, st)]     # (min_dist, vertex)
    heapq.heapify(que)

    while len(que) > 0:
        dist, v0 = heapq.heappop(que)
        if d[v0] < dist: continue
        for v1, dist in g[v0]:
            if d[v1] > d[v0] + dist:
                d[v1] = d[v0] + dist
                heapq.heappush(que, (d[v1], v1))

    return d

def solve(f):
    n, m = f.read_int_list()
    s, t = f.read_int_list()
    g = collections.defaultdict(list)
    for m in xrange(m):
        u, v, d = f.read_int_list()
        g[u-1].append((v-1, d))
        g[v-1].append((u-1, d))

    d = dijkstra(g, n, s-1)

    cand = []
    for i in xrange(n):
        if d[t-1] == d[i]*2: cand.append((i,i))

    memo = [-1]*n
    memo[t-1] = 1

    def count(v):
        if memo[v] >= 0: return memo[v]
        res = 0
        for vi, di in g[v]:
            if d[v]+di == d[vi]:
                if d[v]*2 < d[t-1] < (d[v] + di)*2:
                    cand.append((v, vi))
                res = (res+count(vi))%MOD
        memo[v] = res
        return res

    memo2 = [-1]*n
    memo2[s-1] = 1

    def count2(v):
        if memo2[v] >= 0: return memo2[v]
        res = 0
        for vi, di in g[v]:
            if d[v]-di == d[vi]:
                res = (res+count2(vi))%MOD
        memo2[v] = res
        return res

    count(s-1)
    count2(t-1)

    cnt = []
    for v1, v2 in cand:
        cnt.append((memo2[v1]*memo[v2])%MOD)

    s = sum(cnt)
    ans = 0
    for ci in cnt:
        ans = (ans+ci*(s-ci))%MOD

    return ans


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)