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: Wrong Answer

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
            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: Wrong Answer

Solution code:
from collections import defaultdict
from functools import reduce
import heapq as hq
from sys import stdin
 
MOD = 10**9+7
N,M = map(int,stdin.readline().split())
S,T = map(int,stdin.readline().split())
S,T = S-1,T-1
 
E = defaultdict(list)
lines = stdin.readlines()
for line in lines:
  u,v,d = map(int,line.split())
  E[u-1].append((v-1,d))
  E[v-1].append((u-1,d))
 
dS = [None]*N
dT = [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

  dM = dT if f else dS
  dN = dS if f else dT
  if dM[v] is None:
    dM[v] = d
    for u,dd in E[v]:
      if dM[u] is None and (d+dd)*2 <= D:
        hq.heappush(Q,(d+dd,u,f))
 
  if dN[v] is not None:
    D = min(dN[v]+d,D)
 
del Q

def helper(start,dist):
  cnts = [0]*N
  cnts[start] = 1

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

  return cnts

Sn = helper(S,dS)
Tn = helper(T,dT)


def it():
  for v in range(N):
    if dS[v] is not None:
      ds = dS[v]
      if dT[v] == ds and ds*2 == D:
        yield Sn[v]*Tn[v] % MOD
      else:
        for u,d in E[v]:
          if dT[u] is not None and abs(dT[u]-ds) < d and ds+d+dT[u] == D:
            yield Sn[v]*Tn[u] % MOD


X = list(it())

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

Submission status: Wrong Answer

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

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

E = defaultdict(list)
lines = stdin.readlines()
for line in lines:
  u,v,d = map(int,line.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)

Submission status: Wrong Answer

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


print('unko')
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)

Submission status: Wrong Answer

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

print('unko')

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)

Submission status: Wrong Answer

Solution code:
import scipy.sparse as sps
import scipy.sparse.csgraph as spsc
import numpy as np
from time import process_time as timer

N,M = map(int,input().split())

S,T = map(int,input().split())
S,T = S-1,T-1

E = sps.dok_matrix((N,N),dtype=int)

def it():
  for _ in range(M):
    u,v,d = map(int,input().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

print('unko')

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] % MOD)**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: Wrong Answer

Solution code:
import scipy.sparse as sps
import scipy.sparse.csgraph as spsc
import numpy as np
from time import process_time as timer

N,M = map(int,input().split())

S,T = map(int,input().split())
S,T = S-1,T-1

E = sps.dok_matrix((N,N),dtype=int)

def it():
  for _ in range(M):
    u,v,d = map(int,input().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]

E = tuple((u,v) for u,v,d in ((u,v,d) if dS[u] <= dS[v] else (v,u,d) 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 _,u,v in edges:
    cnts[v] += cnts[u]
    cnts[v] %= 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))


c0 = 0

for v in range(N):
  if dS[v]*2 == D:
    c0 += Sn[v]*Tn[v]
    c0 %= MOD

c1 = 0
for u,v in E:
  if dS[u] < dT[u] and dS[v] > dT[v]:
    c1 += Sn[u]*Tn[v]
    c1 %= MOD

total = Sn[T]*Tn[S]
cnt = c0+c1

print((total-cnt)%MOD)

Submission status: Wrong Answer

Solution code:
# E
import heapq

N, M = map(int, input().split())
S, T = map(int, input().split())

G = dict()
for i in range(N):
    G[i] = dict()


# input
for _ in range(M):
    U, V, D = map(int, input().split())
    G[U-1][V-1] = D
    G[V-1][U-1] = D
    
    
# dist from S/T
dist_s = [N*1000000000]*N
cont_s = [0]*N
dist_t = [N*1000000000]*N
cont_t = [0]*N

# used flag
used_ = [0]*N

dist_s[S-1] = 0
cont_s[S-1] = 1

h = []
heapq.heappush(h, (0, S-1))

while True:
    
    # find start
    s = -1
    while len(h) > 0:
        _, s = heapq.heappop(h)
        if used_[s] == 0:
            used_[s] = 1
            break     
    if s == -1:
        break
        
    used_[s] = 1
    
    for t in G[s].keys():
        if dist_s[t] < dist_s[s] + G[s][t]:
            pass
        elif dist_s[t] == dist_s[s] + G[s][t]:
            cont_s[t] += cont_s[s]
        else:
            dist_s[t] = dist_s[s] + G[s][t]
            cont_s[t] = cont_s[s]
            heapq.heappush(h, (dist_s[t], t))
            
# used flag
used_ = [0]*N

dist_t[T-1] = 0
cont_t[T-1] = 1

h = []
heapq.heappush(h, (0, T-1))
while True:
    
    # find start
    s = -1
    while len(h) > 0:
        _, s = heapq.heappop(h)
        if used_[s] == 0:
            used_[s] = 1
            break     
    if s == -1:
        break
    
    for t in G[s].keys():
        if dist_t[t] < dist_t[s] + G[s][t]:
            pass
        elif dist_t[t] == dist_t[s] + G[s][t]:
            cont_t[t] += cont_t[s]
        else:
            dist_t[t] = dist_t[s] + G[s][t]
            cont_t[t] = cont_t[s]
            heapq.heappush(h, (dist_t[t], t))
            
res_total = cont_s[T-1]*cont_t[S-1]

# find points at half
half_time = dist_s[T-1] / 2

# node
for s in range(N):
    if dist_s[s] == half_time and dist_t[s] == half_time:
        res_total -= (cont_s[s]*cont_t[s])**2
    elif dist_s[s] < half_time:
        for t in G[s].keys():
            if dist_s[t] > half_time and dist_s[s] + dist_t[t] + G[s][t] == dist_s[T-1]:
                res_total -= (cont_s[s]*cont_t[t])**2
                
print(res_total)

Submission status: Wrong Answer

Solution code:
import heapq


class AdjacencyList:
    """
    隣接リストで表現される単純グラフ
    """

    def __init__(self, size_v):
        self.size_v = size_v
        self.graph = [[] for i in range(size_v)]

    def add_arc(self, source, target, weight=1):
        self.graph[source].append((target, weight))

    def add_edge(self, source, target, weight=1):
        self.add_arc(source, target, weight)
        self.add_arc(target, source, weight)

    def __str__(self):
        return str(self.graph)

    def dijkstra(self, source=0):
        """
        sourceから全点への距離を求める。
        Time complexity: O((E+V)logV)
        """
        visited = [False] * self.size_v
        distance = [float('inf')] * self.size_v
        hq = [(0, source)]
        while hq:
            weight, vertex = heapq.heappop(hq)
            if visited[vertex]:
                continue
            visited[vertex] = True
            distance[vertex] = weight
            for adjacency_vertex, adjacency_weight in self.graph[vertex]:
                if not visited[adjacency_vertex]:
                    heapq.heappush(
                        hq, (weight + adjacency_weight, adjacency_vertex))
        return distance


def main():
    n, m = map(int, input().split())
    s, t = map(int, input().split())
    graph = AdjacencyList(n)
    for i in range(m):
        u, v, d = map(int, input().split())
        graph.add_edge(u - 1, v - 1, d)
    dist = graph.dijkstra(s - 1)
    dist_rev = graph.dijkstra(t - 1)

    dp = [0 for i in range(n)]
    dp[s - 1] = 1
    hq = [(dist[i], i) for i in range(n)]
    heapq.heapify(hq)
    target_time = dist[t - 1] / 2
    cnt = []
    while hq:
        d, v = heapq.heappop(hq)

        for nv, nd in graph.graph[v]:
            if dist[nv] + nd + dist_rev[v] == dist[t - 1]:
                dp[v] += dp[nv]
                if dist[nv] < target_time < d:
                    cnt.append(dp[nv])

        if d == target_time and dist[v] + dist_rev[v] == dist[t - 1]:
            cnt.append(dp[v])
    # print(dp)
    # print(cnt)
    ret = sum([(dp[t - 1] - c) * c for c in cnt])
    print(ret)
    # print(graph.dijkstra(s-1))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import heapq

N, M = map(int, input().split())
S, T = map(lambda x: int(x) - 1, input().split())

adjList = [[] for i in range(N)]
for i in range(M):
    U, V, D = map(int, input().split())
    adjList[U - 1].append((V - 1, D))
    adjList[V - 1].append((U - 1, D))


numRoute = [[] for i in range(N)]
numRoute[S] = [1]
Done = [False] * N
pq = []

cost = [float('inf')] * N
cost[S] = 0
heapq.heappush(pq, (0, S))

while pq:
    c, vNow = heapq.heappop(pq)
    if c > cost[vNow]: continue
    if Done[vNow]: continue

    for v2, wt in adjList[vNow]:
        c2 = cost[vNow] + wt
        if c2 <= cost[v2]:
            if c2 == cost[v2]:
                numRoute[v2] += [sum(numRoute[vNow])]
            else:
                numRoute[v2] = [sum(numRoute[vNow])]

            cost[v2] = c2
            heapq.heappush(pq, (c2, v2))

    Done[vNow] = True


sumR = sum(numRoute[T])
ans = 0
for R in numRoute[T]:
    ans += R * (sumR - R)
    ans %= 10 ** 9 + 7
print(ans)

Submission status: Wrong Answer

Solution code:
import heapq


class AdjacencyList:
    """
    隣接リストで表現される単純グラフ
    """

    def __init__(self, size_v):
        self.size_v = size_v
        self.graph = [[] for i in range(size_v)]

    def add_arc(self, source, target, weight=1):
        self.graph[source].append((target, weight))

    def add_edge(self, source, target, weight=1):
        self.add_arc(source, target, weight)
        self.add_arc(target, source, weight)

    def __str__(self):
        return str(self.graph)

    def dijkstra(self, source=0):
        """
        sourceから全点への距離を求める。
        Time complexity: O((E+V)logV)
        """
        visited = [False] * self.size_v
        distance = [float('inf')] * self.size_v
        hq = [(0, source)]
        while hq:
            weight, vertex = heapq.heappop(hq)
            if visited[vertex]:
                continue
            visited[vertex] = True
            distance[vertex] = weight
            for adjacency_vertex, adjacency_weight in self.graph[vertex]:
                if not visited[adjacency_vertex]:
                    heapq.heappush(
                        hq, (weight + adjacency_weight, adjacency_vertex))
        return distance


def main():
    n, m = map(int, input().split())
    s, t = map(int, input().split())
    graph = AdjacencyList(n)
    for i in range(m):
        u, v, d = map(int, input().split())
        graph.add_edge(u - 1, v - 1, d)
    dist = graph.dijkstra(s - 1)
    dist_rev = graph.dijkstra(t - 1)

    dp = [0 for i in range(n)]
    dp[s - 1] = 1
    hq = [(dist[i], i) for i in range(n)]
    heapq.heapify(hq)
    target_time = dist[t - 1] / 2
    cnt = []
    while hq:
        d, v = heapq.heappop(hq)

        for nv, nd in graph.graph[v]:
            if dist[nv] + nd + dist_rev[v] == dist[t - 1]:
                dp[v] += dp[nv]
                if dist[nv] < target_time < dist[nv] + nd and dist[v] + dist_rev[v] == dist[t - 1]:
                    # print(v, nv)
                    cnt.append(dp[nv])

        if d == target_time and dist[v] + dist_rev[v] == dist[t - 1]:
            cnt.append(dp[v])
    # print(dp)
    # print(cnt)
    ret = sum([(dp[t - 1] - c) * c for c in cnt])
    print(ret)
    # print(graph.dijkstra(s-1))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import heapq


class AdjacencyList:
    """
    隣接リストで表現される単純グラフ
    """

    def __init__(self, size_v):
        self.size_v = size_v
        self.graph = [[] for i in range(size_v)]

    def add_arc(self, source, target, weight=1):
        self.graph[source].append((target, weight))

    def add_edge(self, source, target, weight=1):
        self.add_arc(source, target, weight)
        self.add_arc(target, source, weight)

    def __str__(self):
        return str(self.graph)
    

    def dijkstra(self, source=0):
        """
        sourceから全点への距離を求める。
        Time complexity: O((E+V)logV)
        """
        visited = [False] * self.size_v
        distance = [float('inf')] * self.size_v
        hq = [(0, source)]
        while hq:
            weight, vertex = heapq.heappop(hq)
            if visited[vertex]:
                continue
            visited[vertex] = True
            distance[vertex] = weight
            for adjacency_vertex, adjacency_weight in self.graph[vertex]:
                if not visited[adjacency_vertex]:
                    heapq.heappush(hq, (weight + adjacency_weight, adjacency_vertex))
        return distance


def main():
    n, m = map(int, input().split())
    s, t = map(int, input().split())
    graph = AdjacencyList(n)
    for i in range(m):
        u, v, d = map(int, input().split())
        graph.add_edge(u - 1, v - 1, d)
    dist = graph.dijkstra(s-1)
    dist_rev = graph.dijkstra(t-1)

    dp = [0 for i in range(n)]
    dp[s-1] = 1
    hq = [(dist[i], i) for i in range(n)]
    heapq.heapify(hq)
    target_time = dist[t-1] / 2
    cnt = []
    while hq:
        d,v = heapq.heappop(hq)
            
        for nv, nd in graph.graph[v]:
            if dist[nv] + nd == d:
                dp[v] += dp[nv]
                if dist[nv] < target_time < dist[nv] + nd and dist[v] + dist_rev[v] == dist[t-1]:
                    # print(v, nv)
                    cnt.append(dp[nv])

        if d == target_time and dist[v] + dist_rev[v] == dist[t-1]:
            cnt.append(dp[v])
    # print(dp)
    # print(cnt)
    ret = sum([(dp[t-1] - c) * c for c in cnt])
    print(ret)
    # print(graph.dijkstra(s-1))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
MOD = 10**9 + 7

n, m = map(int, input().split())
a, b = map(int, input().split())
s = [[] for i in range(n)]
a, b = a - 1, b - 1
for i in range(m):
    x, y, d = map(int, input().split())
    x -= 1
    y -= 1
    s[x].append((y, d))
    s[y].append((x, d))

da, db = [-1 for i in range(n)], [-1 for i in range(n)]
na, nb = [0 for i in range(n)], [0 for i in range(n)]

def dij(poc, sol, ways):
    sol[poc] = 0
    heap = []
    heappush(heap, (0, poc))
    while heap:
        dist, x = heappop(heap)
        if sol[x] != dist: continue
        for y, d in s[x]:
            if sol[y] == -1 or sol[y] > sol[x] + d:
                sol[y] = sol[x] + d
                ways[y] = ways[x]
                heappush(heap, (sol[y], y))
            elif sol[y] == sol[x] + d:
                ways[y] += ways[x]

na[a] = nb[b] = 1
dij(a, da, na)
dij(b, db, nb)

t = da[b]
assert da[b] == db[a]
assert na[b] == nb[a]

tot = 0
for x in range(n):
    if da[x] * 2 == t and db[x] * 2 == t:
        tot += na[x] * nb[x]
    for y, d in s[x]:
        if da[x] * 2 < t and db[y] * 2 < t and da[x] + d + db[y] == t:
            tot += na[x] * nb[y]

print((na[b] * nb[a] - tot % MOD + MOD) % MOD)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
MOD = 10**9 + 7

n, m = map(int, input().split())
a, b = map(int, input().split())
s = [[] for i in range(n)]
a, b = a - 1, b - 1
for i in range(m):
    x, y, d = map(int, input().split())
    x -= 1
    y -= 1
    s[x].append((y, d))
    s[y].append((x, d))

da, db = [-1 for i in range(n)], [-1 for i in range(n)]
na, nb = [0 for i in range(n)], [0 for i in range(n)]

def dij(poc, sol, ways):
    sol[poc] = 0
    heap = []
    heappush(heap, (0, poc))
    while heap:
        dist, x = heappop(heap)
        if sol[x] != dist: continue
        ways[x] %= MOD
        for y, d in s[x]:
            if sol[y] == -1 or sol[y] > sol[x] + d:
                sol[y] = sol[x] + d
                ways[y] = ways[x]
                heappush(heap, (sol[y], y))
            elif sol[y] == sol[x] + d:
                ways[y] += ways[x]

na[a] = nb[b] = 1
dij(a, da, na)
dij(b, db, nb)

t = da[b]
assert da[b] == db[a]
assert na[b] == nb[a]

tot = 0
for x in range(n):
    if da[x] * 2 == t and db[x] * 2 == t:
        tot += na[x] * nb[x]
    for y, d in s[x]:
        if da[x] * 2 < t and db[y] * 2 < t and da[x] + d + db[y] == t:
            tot += na[x] * nb[y]

print((na[b] * nb[a] - tot % MOD + MOD) % MOD)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
MOD = 10**9 + 7

n, m = map(int, input().split())
a, b = map(int, input().split())
s = [[] for i in range(n)]
a, b = a - 1, b - 1
for i in range(m):
    x, y, d = map(int, input().split())
    x -= 1
    y -= 1
    s[x].append((y, d))
    s[y].append((x, d))

da, db = [-1 for i in range(n)], [-1 for i in range(n)]
na, nb = [0 for i in range(n)], [0 for i in range(n)]

def dij(poc, sol, ways):
    sol[poc] = 0
    heap = []
    heappush(heap, (0, poc))
    while heap:
        dist, x = heappop(heap)
        if sol[x] != dist: continue
        ways[x] %= MOD
        for y, d in s[x]:
            if sol[y] == -1 or sol[y] > dist + d:
                sol[y] = dist + d
                ways[y] = ways[x]
                heappush(heap, (sol[y], y))
            elif sol[y] == dist + d:
                ways[y] += ways[x]

na[a] = nb[b] = 1
dij(a, da, na)
dij(b, db, nb)

t = da[b]
assert da[b] == db[a]
assert na[b] == nb[a]

tot = na[b] * nb[a]
for x in range(n):
    if da[x] * 2 == t and db[x] * 2 == t:
        tot += MOD - (na[x] * nb[x]) % MOD
    for y, d in s[x]:
        if da[x] * 2 < t and db[y] * 2 < t and da[x] + d + db[y] == t:
            tot += MOD - (na[x] * nb[y]) % MOD

print(tot % MOD)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
MOD = 10**9 + 7

n, m = map(int, input().split())
a, b = map(int, input().split())
s = [[] for i in range(n)]
a, b = a - 1, b - 1
for i in range(m):
    x, y, d = map(int, input().split())
    x -= 1
    y -= 1
    s[x].append((y, d))
    s[y].append((x, d))

da, db = [-1 for i in range(n)], [-1 for i in range(n)]
na, nb = [0 for i in range(n)], [0 for i in range(n)]

def dij(poc, sol):
    sol[poc] = 0
    heap = []
    heappush(heap, (0, poc))
    while heap:
        _, x = heappop(heap)
        for y, d in s[x]:
            if sol[y] == -1 or sol[y] > sol[x] + d:
                sol[y] = sol[x] + d
                heappush(heap, (sol[y], y))

def ways(poc, dist, sol):
    sol[poc] = 1
    red = sorted([(dist[x], x) for x in range(n)])
    for _, x in red:
        for y, d in s[x]:
            if dist[y] == dist[x] + d:
                sol[y] = (sol[y] + sol[x]) % MOD

dij(a, da)
ways(a, da, na)
dij(b, db)
ways(b, db, nb)

t = da[b]
assert da[b] == db[a]
assert na[b] == nb[a]

tot = na[b] * nb[a]
for x in range(n):
    if da[x] * 2 == t and db[x] * 2 == t:
        tot += MOD - (na[x] * nb[x]) % MOD
    for y, d in s[x]:
        if da[x] * 2 < t and db[y] * 2 < t and da[x] + d + db[y] == t:
            tot += MOD - (na[x] * nb[y]) % MOD

print(tot % MOD)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop

n, m = map(int, input().split())
a, b = map(int, input().split())
s = [[] for i in range(n)]
a, b = a - 1, b - 1
for i in range(m):
    x, y, d = map(int, input().split())
    x -= 1
    y -= 1
    s[x].append((y, d))
    s[y].append((x, d))

da, db = [-1 for i in range(n)], [-1 for i in range(n)]

def dij(poc, sol):
    sol[poc] = 0
    heap = []
    heappush(heap, (0, poc))
    while heap:
        _, x = heappop(heap)
        for y, d in s[x]:
            if sol[y] == -1 or sol[y] > sol[x] + d:
                sol[y] = sol[x] + d
                heappush(heap, (sol[y], y))

dij(a, da)
dij(b, db)
t = da[b]
assert da[b] == db[a]
cnt = 0
for x in range(n):
    #print(x + 1, da[x], db[x])
    cnt += (da[x] * 2 == t and db[x] * 2 == t)
    for y, d in s[x]:
        cnt += (da[x] * 2 < t and db[y] * 2 < t and\
                da[x] + d + db[y] == t)
print(cnt * (cnt - 1) % 1000000007)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop

n, m = map(int, input().split())
a, b = map(int, input().split())
s = [[] for i in range(n)]
a, b = a - 1, b - 1
for i in range(m):
    x, y, d = map(int, input().split())
    x -= 1
    y -= 1
    s[x].append((y, d))
    s[y].append((x, d))

da, db = [-1 for i in range(n)], [-1 for i in range(n)]

def dij(poc, sol):
    sol[poc] = 0
    heap = []
    heappush(heap, (0, poc))
    while heap:
        _, x = heappop(heap)
        for y, d in s[x]:
            if sol[y] == -1 or sol[y] > sol[x] + d:
                sol[y] = sol[x] + d
                heappush(heap, (sol[y], y))

dij(a, da)
dij(b, db)
t = da[b]
assert da[b] == db[a]
cnt = 0
for x in range(n):
    #print(x + 1, da[x], db[x])
    cnt += (da[x] * 2 == t and db[x] * 2 == t)
    for y, d in s[x]:
        cnt += (da[x] * 2 < t and db[y] * 2 < t and\
                da[x] + d + db[y] == t)
print(cnt * (cnt - 1))

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
from collections import defaultdict
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    md = 10 ** 9 + 7
    inf = 10 ** 15
    to = defaultdict(list)
    n, m = map(int, input().split())
    s, t = map(int1, input().split())
    for ei in range(m):
        u, v, d = map(int, input().split())
        u, v = u - 1, v - 1
        to[u].append([v, d])
        to[v].append([u, d])

    # sからのダイクストラで
    # 各頂点までの最短距離dists
    # sからのルート数way_s
    # 逆向きのダグot
    # 以上を作る
    dists = [inf] * n
    way_s = [0] * n
    ot = defaultdict(list)
    hp = []
    heappush(hp, [0, s])
    way_s[s] = 1
    u = -1
    while u != t:
        dist, u = heappop(hp)
        if dists[u] != inf: continue
        dists[u] = dist
        for v, d in to[u]:
            if dists[v] == inf:
                heappush(hp, [dist + d, v])
            elif dists[v] == dist - d:
                way_s[u] += way_s[v]
                ot[u].append(v)
    #print(dists)
    #print(way_s)
    #print(ot)

    # tからのbfsで
    # sからのルート数way_tを作りながら
    # 衝突するルート数way_colを計算していく
    way_t = [0] * n
    way_col = 0
    half = dists[t] / 2
    way_t[t] = 1
    hp = []
    heappush(hp, [-dists[t], t])
    while hp:
        dist, u = heappop(hp)
        if -dist == half:
            way_col += pow(way_t[u] * way_s[u], 2, md)
            way_col %= md
            continue
        way = way_t[u]
        for v in ot[u]:
            if dists[v] < half:
                way_col += pow(way_t[u] * way_s[v], 2, md)
                way_col %= md
            else:
                way_t[v] += way
                heappush(hp, [-dists[v], v])
    #print(way_col)

    # 全ルートから衝突するルートを引いて答え
    ans = pow(way_s[t], 2, md) - way_col
    ans %= md
    print(ans)

main()