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:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    s,t = LI()
    e = collections.defaultdict(list)
    for _ in range(m):
        u,v,d = LI()
        e[u].append((v,d))
        e[v].append((u,d))

    def search(s,t):
        d = collections.defaultdict(lambda: [inf, 0])
        d[s] = [0, 1]
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            uc = d[u][1]

            for uv, ud in e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv][0] > vd:
                    d[uv] = [vd, uc]
                    heapq.heappush(q, (vd, uv))
                elif d[uv][0] == vd:
                    d[uv][1] += uc

        return d

    d1 = search(s,t)
    d2 = search(t,s)
    rd = d1[t][0]
    kk = rd / 2.0

    r = d1[t][1] ** 2 % mod
    for k in list(d1.keys()):
        t,c = d1[k]
        if t > kk:
            continue
        if t == kk:
            if d2[k][0] == t:
                r -= (c**2 * d2[k][1]**2) % mod
            continue

        for uv, ud in e[k]:
            if d2[uv][0] >= kk or t + ud + d2[uv][0] != rd:
                continue
            r -= (c**2 * d2[uv][1]**2) % mod

    return r % mod




print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    s,t = LI()
    e = collections.defaultdict(list)
    for _ in range(m):
        u,v,d = LI()
        e[u].append((v,d))
        e[v].append((u,d))

    def search(s,t):
        d = collections.defaultdict(lambda: [inf, 0])
        d[s] = [0, 1]
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            uc = d[u][1]

            for uv, ud in e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv][0] > vd:
                    d[uv] = [vd, uc]
                    heapq.heappush(q, (vd, uv))
                elif d[uv][0] == vd:
                    d[uv][1] += uc

        return d

    d1 = search(s,t)
    d2 = search(t,s)
    rd = d1[t][0]
    kk = rd / 2.0

    r = d1[t][1] ** 2
    for k in list(d1.keys()):
        t,c = d1[k]
        if t > kk:
            continue
        if t == kk:
            if d2[k][0] == t:
                r -= c**2 * d2[k][1]**2
            continue

        for uv, ud in e[k]:
            if d2[uv][0] >= kk or t + ud + d2[uv][0] != rd:
                continue
            r -= c**2 * d2[uv][1]**2

    return r % mod




print(main())

Submission status: Time Limit Exceeded

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(100000)
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]:
                c = count(vi)
                res = (res+c)%MOD
                if c > 0 and d[v]*2 < d[t-1] < (d[v] + di)*2:
                    cand.append((v, vi))
        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)

Submission status: Time Limit Exceeded

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(100000)
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)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
from collections import deque
N, M = map(int, input().split())
S, T = map(int, input().split())
S -= 1; T -= 1
G = [[] for i in range(N)]
for i in range(M):
    u, v, d = map(int, input().split())
    G[u-1].append((v-1, d))
    G[v-1].append((u-1, d))

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

dist = [INF]*N
dist[S] = 0
que = [(0, S)]
while que:
    cost, v = heappop(que)
    if dist[v] < cost:
        continue
    for w, c in G[v]:
        if cost + c < dist[w]:
            dist[w] = cost + c
            heappush(que, (cost + c, w))

que = deque()
mi = [0]*N
que.append(T)
mi[T] = 1
H = [[] for i in range(N)]
RH = [[] for i in range(N)]

D = dist[T]

V = []
E = []
while que:
    v = que.popleft()
    d = dist[v]
    if d*2 == D:
        V.append(v)
    for w, c in G[v]:
        if d == dist[w] + c:
            if dist[w]*2 < D < d*2:
                E.append((w, v))
            H[v].append(w)
            RH[w].append(v)
            if mi[w] == 0:
                mi[w] = 1
                que.append(w)

def bfs(G, RG, s):
    *deg, = map(len, RG)
    que = deque([s])
    res = [0]*N
    res[s] = 1
    while que:
        v = que.popleft()
        for w in G[v]:
            deg[w] -= 1
            res[w] += res[v]
            if deg[w] == 0:
                que.append(w)
                res[w] %= MOD
    return res
CT = bfs(H, RH, T)
CS = bfs(RH, H, S)

ans = CS[T] * CT[S] % MOD
for v in V:
    ans -= (CS[v] * CT[v]) ** 2
    ans %= MOD
for v, w in E:
    ans -= (CS[v] * CT[w]) ** 2
    ans %= MOD
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

n,m = map(int, input().split())
s,g = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, d))
def search(start, goal):
    q = [[start]]
    q_d = [0]
    min_time = 10**9*m
    num_pass = 0
    #dist_all = [None for i in range(n)]
    while(len(q) > 0):
        path = q.pop(0)
        dist = q_d.pop(0)
        w = path[len(path) - 1]
        if w == goal:
            if min_time >= dist:
                min_time = dist
                num_pass += 1
        else:
            for x in adj_list[w]:
                if x[0] not in path:
                    new_path = path[:]
                    new_path.append(x[0])
                    q.append(new_path)
                    q_d.append(dist + x[1])
    return num_pass

num = search(s-1, g-1)
print(num * (num - 1))

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(200000)
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: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush

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


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


def solve(s, t, links):
    q = [(0, 0, s, -1, 0), (0, 0, t, -1, 1)]
    visited_fwd, visited_bwd = [INF] * n, [INF] * n
    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
        else:
            visited_self = visited_fwd
            visited_opp = visited_bwd

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

        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:
            continue
        if cost_a == collision_time:
            collision_nodes.add(a)
        elif cost == collision_time:
            collision_nodes.add(v)
        else:
            collision_links.add((v, a) if is_bwd else (a, v))

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

    for v in collision_nodes:
        if visited_fwd[v] == visited_bwd[v]:
            r = counts_fwd[v] * counts_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 = counts_fwd[u] * counts_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 _ 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: Time Limit Exceeded

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

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))

    collision_time = limit / 2
    while q:
        cost, v, is_bwd = heappop(q)
        if cost > collision_time:
            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

    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 = [[] for _ in range(n)]
for uvd in sys.stdin.readlines():
    u, v, d = map(int, uvd.split())
    u -= 1
    v -= 1
    links[u].append((d, v))
    links[v].append((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

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

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] % MOD
            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] % MOD
                    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 = [[] for _ in range(n)]
for uvd in sys.stdin.readlines():
    u, v, d = map(int, uvd.split())
    u -= 1
    v -= 1
    links[u].append((d, v))
    links[v].append((d, u))
print(solve(s, t, links))

Submission status: Time Limit Exceeded

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

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] % MOD
            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] % MOD
                    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, sys.stdin.readline().split())
s, t = map(int, sys.stdin.readline().split())
s -= 1
t -= 1
links = [set() for _ in range(n)]
for uvd in sys.stdin.readlines():
    u, v, d = map(int, uvd.split())
    u -= 1
    v -= 1
    links[u].add((d, v))
    links[v].add((d, u))
print(solve(s, t, links))