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: Time Limit Exceeded

Solution code:
from bisect import bisect
from heapq import heappop, heappush

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


def count_routes(visited, s, links):
    counts = [0] * n
    counts[s] = 1
    dists = [(d, v) for v, d in enumerate(visited) if d != INF]
    dists.sort()
    for dv, v in dists:
        for du, u in links[v]:
            if dv + du == visited[u]:
                counts[u] += counts[v]
                counts[u] %= MOD
    return dists, counts


def solve(s, t, links):
    q = [(0, s, 0), (0, t, 1)]
    visited_fwd, visited_bwd = [INF] * n, [INF] * n
    limit = 0
    while q:
        cost, v, is_bwd = heappop(q)
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd

        pre_cost = visited_self[v]
        if pre_cost == INF:
            visited_self[v] = cost
        elif cost > pre_cost:
            continue

        cost_opp = visited_opp[v]
        if cost_opp != INF:
            limit = cost + cost_opp
            break

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

    while q:
        cost, v, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited_bwd if is_bwd else visited_fwd
        if cost < visited_self[v]:
            visited_self[v] = cost

    dists_fwd, counts_fwd = count_routes(visited_fwd, s, links)
    dists_bwd, counts_bwd = count_routes(visited_bwd, t, links)
    shortest_count = 0
    collision_count = 0

    collision_time = limit / 2
    for d_fwd, v in dists_fwd[:bisect(dists_fwd, (collision_time, n))]:
        d_bwd = visited_bwd[v]
        if d_fwd == d_bwd:
            r = counts_fwd[v] * counts_bwd[v]
            shortest_count += r
            shortest_count %= MOD
            collision_count += pow(r, 2, MOD)
            collision_count %= MOD
        else:
            ct = collision_time - d_fwd
            lt = limit - d_fwd
            for dl, u in links[v]:
                if dl > ct and dl + visited_bwd[u] == lt:
                    r = counts_fwd[v] * counts_bwd[u]
                    shortest_count += r
                    shortest_count %= MOD
                    collision_count += pow(r, 2, MOD)
                    collision_count %= MOD

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect
from heapq import heappop, heappush


def solve(s, t, links):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited_fwd, visited_bwd = [float('inf')] * n, [float('inf')] * n
    pattern_fwd, pattern_bwd = [0] * n, [0] * n
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
            pattern_self = pattern_bwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd
            pattern_self = pattern_fwd
        if visited_self[v] < cost:
            continue
        visited_self[v] = cost
        pattern_self[v] += 1

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

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

    q.sort()
    for cost, v, a, is_bwd in q[:bisect(q, (limit, n))]:
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
            pattern_self = pattern_bwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd
            pattern_self = pattern_fwd

        if visited_self[v] < cost:
            continue
        visited_self[v] = cost
        pattern_self[v] += 1

        cost_opp = visited_opp[v]
        if cost_opp < INF:
            if limit < cost + cost_opp or a in collision_nodes:
                continue
            if cost == cost_opp:
                collision_nodes.add(v)
            else:
                collision_pairs.add((v, a) if is_bwd else (a, v))

    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = pattern_fwd[v], pattern_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
    collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = pattern_fwd[u], pattern_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush


def solve(s, t, links):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited_fwd, visited_bwd = [float('inf')] * n, [float('inf')] * n
    patterns_fwd, patterns_bwd = [0] * n, [0] * n
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
            patterns_self = patterns_bwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd
            patterns_self = patterns_fwd

        if visited_self[v] < cost:
            continue

        visited_self[v] = cost
        patterns_self[v] += 1

        cost_opp = visited_opp[v]
        if cost_opp < INF:
            if limit < cost + cost_opp or a in collision_nodes:
                break
            limit = cost + cost_opp
            if cost == cost_opp:
                collision_nodes.add(v)
            else:
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

        for du, u in links[v]:
            nc = cost + du
            if nc * 2 > limit or visited_self[u] < nc:
                continue
            heappush(q, (nc, u, v, is_bwd))

    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
            patterns_self = patterns_bwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd
            patterns_self = patterns_fwd

        if visited_self[v] < cost:
            continue
        visited_self[v] = cost
        patterns_self[v] += 1

        cost_opp = visited_opp[v]
        if cost_opp < INF:
            if limit < cost + cost_opp or a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                collision_nodes.add(v)
            else:
                collision_pairs.add((v, a) if is_bwd else (a, v))

    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = patterns_fwd[v], patterns_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
    collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = patterns_fwd[u], patterns_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush


def solve(s, t, links):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited_fwd, visited_bwd = [float('inf')] * n, [float('inf')] * n
    patterns_fwd, patterns_bwd = [0] * n, [0] * n
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        if is_bwd:
            visited_self = visited_bwd
            visited_opp = visited_fwd
            patterns_self = patterns_bwd
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd
            patterns_self = patterns_fwd

        if visited_self[v] < cost:
            continue

        visited_self[v] = cost
        patterns_self[v] += 1

        cost_opp = visited_opp[v]
        if cost_opp < INF:
            if limit < cost + cost_opp:
                continue
            if a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_nodes.add(v)
            else:
                # print('add', v, a)
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

        if cost * 2 <= limit:
            for du, u in links[v]:
                nc = cost + du
                if nc * 2 > limit or visited_self[u] < nc:
                    continue
                heappush(q, (nc, u, v, is_bwd))

    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = patterns_fwd[v], patterns_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
    collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = patterns_fwd[u], patterns_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush


def solve(s, t, links):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited = [[float('inf')] * n, [float('inf')] * n]
    patterns = [[0] * n, [0] * n]
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        visited_self = visited[is_bwd]
        if visited_self[v] < cost:
            continue

        visited_self[v] = cost
        patterns[is_bwd][v] += 1

        cost_opp = visited[is_bwd ^ 1][v]
        if cost_opp < INF:
            if limit < cost + cost_opp:
                continue
            if a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_nodes.add(v)
            else:
                # print('add', v, a)
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

        if cost * 2 <= limit:
            for du, u in links[v]:
                nc = cost + du
                if nc * 2 > limit or visited_self[u] < nc:
                    continue
                heappush(q, (nc, u, v, is_bwd))

    patterns_fwd, patterns_bwd = patterns
    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = patterns_fwd[v], patterns_bwd[v]
        shortest_count += r1 * r2
        collision_count += pow(r1 * r2, 2, MOD)
    shortest_count %= MOD
    collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = patterns_fwd[u], patterns_bwd[v]
        shortest_count += r1 * r2
        collision_count += pow(r1 * r2, 2, MOD)
    # print(limit)
    # print(visited)
    # print(ancestors)
    # print(collision_nodes)
    # print(collision_pairs)
    # print(collision_count, shortest_count)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush


def solve(s, t, links):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited = [[float('inf')] * n, [float('inf')] * n]
    patterns = [[0] * n, [0] * n]
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited[is_bwd]
        # print(is_bwd, cost, v, a, visited_self)
        if visited_self[v] < cost:
            continue

        visited_self[v] = cost
        patterns[is_bwd][v] += 1

        cost_opp = visited[is_bwd ^ 1][v]
        if cost_opp < INF:
            if limit < cost + cost_opp:
                continue
            if a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_nodes.add(v)
            else:
                # print('add', v, a)
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

        if cost * 2 <= limit:
            for du, u in links[v]:
                nc = cost + du
                if nc * 2 > limit or visited_self[u] < nc:
                    continue
                heappush(q, (nc, u, v, is_bwd))

    patterns_fwd, patterns_bwd = patterns
    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = patterns_fwd[v], patterns_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = patterns_fwd[u], patterns_bwd[v]
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    # print(limit)
    # print(visited)
    # print(ancestors)
    # print(collision_nodes)
    # print(collision_pairs)
    # print(collision_count, shortest_count)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush


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):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited = [[float('inf')] * n, [float('inf')] * n]
    ancestors = [[set() for _ in range(n)], [set() for _ in range(n)]]
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited[is_bwd]
        # print(is_bwd, cost, v, a, visited_self)
        if visited_self[v] < cost:
            continue

        visited_self[v] = cost
        ancestors[is_bwd][v].add(a)

        cost_opp = visited[is_bwd ^ 1][v]
        if cost_opp < INF:
            if limit < cost + cost_opp:
                continue
            if a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_nodes.add(v)
            else:
                # print('add', v, a)
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

        if cost * 2 <= limit:
            for du, u in links[v]:
                nc = cost + du
                if nc * 2 > limit or visited_self[u] < nc:
                    continue
                heappush(q, (nc, u, v, is_bwd))

    get_patterns_fwd = get_patterns_func(s, ancestors[0])
    get_patterns_bwd = get_patterns_func(t, ancestors[1])
    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = get_patterns_fwd(v), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = get_patterns_fwd(u), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    # print(limit)
    # print(visited)
    # print(ancestors)
    # print(collision_nodes)
    # print(collision_pairs)
    # print(collision_count, shortest_count)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush


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):
    MOD, INF = 1000000007, float('inf')
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited = [[float('inf')] * n, [float('inf')] * n]
    ancestors = [[set() for _ in range(n)], [set() for _ in range(n)]]
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited[is_bwd]
        # print(is_bwd, cost, v, a, visited_self)
        if visited_self[v] < cost:
            continue

        visited_self[v] = cost
        ancestors[is_bwd][v].add(a)

        cost_opp = visited[is_bwd ^ 1][v]
        if cost_opp < INF:
            if limit < cost + cost_opp:
                continue
            if a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_nodes.add(v)
            else:
                # print('add', v, a)
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

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

    get_patterns_fwd = get_patterns_func(s, ancestors[0])
    get_patterns_bwd = get_patterns_func(t, ancestors[1])
    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = get_patterns_fwd(v), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = get_patterns_fwd(u), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    # print(limit)
    # print(visited)
    # print(ancestors)
    # print(collision_pair)
    # print(collision_count, shortest_count)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

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


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):
    MOD = 1000000007
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited = [{}, {}]
    ancestors = [defaultdict(set), defaultdict(set)]
    limit = float('inf')
    collision_nodes = set()
    collision_pairs = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited[is_bwd]
        # print(is_bwd, cost, v, a, visited_self)
        if v in visited_self and visited_self[v] < cost:
            continue

        visited_self[v] = cost
        ancestors[is_bwd][v].add(a)

        visited_opp = visited[is_bwd ^ 1]
        if v in visited_opp:
            cost_opp = visited_opp[v]
            if limit < cost + cost_opp:
                continue
            if a in collision_nodes:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_nodes.add(v)
            else:
                # print('add', v, a)
                collision_pairs.add((v, a) if is_bwd else (a, v))
            continue

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

    get_patterns_fwd = get_patterns_func(s, ancestors[0])
    get_patterns_bwd = get_patterns_func(t, ancestors[1])
    shortest_count = 0
    collision_count = 0

    for v in collision_nodes:
        r1, r2 = get_patterns_fwd(v), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    for u, v in collision_pairs:
        r1, r2 = get_patterns_fwd(u), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    # print(limit)
    # print(visited)
    # print(ancestors)
    # print(collision_pair)
    # print(collision_count, shortest_count)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

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


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):
    MOD = 1000000007
    q = [(0, s, -1, 0), (0, t, -1, 1)]
    visited = [{}, {}]
    ancestors = [defaultdict(set), defaultdict(set)]
    limit = float('inf')
    collision_pair = set()
    while q:
        cost, v, a, is_bwd = heappop(q)
        if cost > limit:
            break
        visited_self = visited[is_bwd]
        # print(is_bwd, cost, v, a, visited_self)
        if v in visited_self and visited_self[v] < cost:
            continue

        visited_self[v] = cost
        ancestors[is_bwd][v].add(a)

        visited_opp = visited[is_bwd ^ 1]
        if v in visited_opp:
            cost_opp = visited_opp[v]
            if limit < cost + cost_opp:
                continue
            if (a, a) in collision_pair:
                continue
            limit = cost + cost_opp
            if cost == cost_opp:
                # print('add', v)
                collision_pair.add((v, v))
            else:
                # print('add', v, a)
                collision_pair.add((v, a) if is_bwd else (a, v))
            continue

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

    get_patterns_fwd = get_patterns_func(s, ancestors[0])
    get_patterns_bwd = get_patterns_func(t, ancestors[1])
    shortest_count = 0
    collision_count = 0

    for u, v in collision_pair:
        r1, r2 = get_patterns_fwd(u), get_patterns_bwd(v)
        shortest_count += r1 * r2
        shortest_count %= MOD
        collision_count += pow(r1 * r2, 2, MOD)
        collision_count %= MOD
    # print(limit)
    # print(visited)
    # print(ancestors)
    # print(collision_pair)
    # print(collision_count, shortest_count)

    return (pow(shortest_count, 2, MOD) - collision_count) % MOD


n, m = map(int, input().split())
s, t = map(int, input().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for _ in range(m):
    u, v, d = map(int, input().split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

Solution code:
import scipy.sparse as sps
import scipy.sparse.csgraph as spsc
import numpy as np
from sys import stdin
 
N,M = map(int,stdin.readline().split())
 
S,T = map(int,stdin.readline().split())
S,T = S-1,T-1
 
E = sps.dok_matrix((N,N),dtype=int)
 
def it():
  lines = stdin.readlines()
  for line in lines:
    u,v,d = map(int,line.split())
    u,v = u-1,v-1
    yield ((u,v),d)
E.update(it())
 
 
dS,dT = spsc.dijkstra(E,directed=False, indices=[S,T]).astype(int)
D = dS[T]
D2 = D//2
 
E = tuple((u,v) for d,u,v in ((d,u,v) if dS[u] <= dS[v] else (d,v,u) for (u,v),d in E.items()) if dS[u]+d+dT[v] == D)
 
MOD = 10**9+7
 
 
def helper(start, edges):
  cnts = [0]*N
  cnts[start] = 1
  for d,u,v in edges:
    cnts[v] = (cnts[v] + cnts[u]) % MOD
  return cnts
 
 
Sn = helper(S,sorted((dS[u],u,v) for u,v in E))
Tn = helper(T,sorted((dT[v],v,u) for u,v in E))
 
from functools import reduce
 
def it():
  for v in range(N):
    if dS[v] == D2:
      yield (Sn[v]*Tn[v])**2
 
c0 = reduce(lambda x,y: (x+y)%MOD, it(), 0) if D%2==0 else 0
 
diff = dS-dT
 
def it():
  for u,v in E:
    if diff[u] < 0 < diff[v]:
      yield (Sn[u]*Tn[v])**2
 
c1 = reduce(lambda x,y: (x+y)%MOD, it(), 0)
 
total = Sn[T]*Tn[S]
cnt = c0+c1
 
print((total-cnt)%MOD)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from functools import reduce
import heapq as hq

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

E = defaultdict(list)

for _ in range(M):
  u,v,d = map(int,input().split())
  E[u-1].append((v-1,d))
  E[v-1].append((u-1,d))

dist = [None]*N
flag = [None]*N

Q = [(0,S,False),(0,T,True)]

D = float('inf')

while Q:
  d,v,f = hq.heappop(Q)
  if d*2 > D:
    break
  if flag[v] is None:
    flag[v] = f
    dist[v] = d
    for u,dd in E[v]:
      if flag[u] != f:
        hq.heappush(Q,(d+dd,u,f))

  elif flag[v] != f:
    D = min(dist[v]+d,D)

del Q


cnts = [0]*N
cnts[S] = 1
cnts[T] = 1

for d,v in sorted((d,v) for v,d in enumerate(dist) if d is not None):
  f = flag[v]
  c = cnts[v]
  for u,dd in E[v]:
    if f == flag[u] and d+dd == dist[u]:
      cnts[u] = (cnts[u]+c)%MOD

def it():
  for v in range(N):
    for u,d in E[v]:
      if flag[v] == True and flag[u] == False and dist[v]+d+dist[u] == D:
        yield cnts[u]*cnts[v] % MOD
X = list(it())

total = reduce(lambda a,b:(a+b)%MOD, X)
total = total*total % MOD

sub = reduce(lambda a,b:(a+b)%MOD, map(lambda x: x*x % MOD, X))

print((total-sub)%MOD)