-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathC.py
69 lines (56 loc) · 1.25 KB
/
C.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from collections import Counter
n = int(input())
a, b = map(int, input().split())
m =int(input())
xy = [list(map(int, input().split())) for _ in range(m)]
def topsort(G):
Q = []
count = dict((u, 0) for u in range(len(G)))
for u in range(len(G)):
for v in G[u]:
count[v] += 1
for u in range(len(G)):
if count[u] == 0:
Q.append(u)
anslst = []
while Q:
u = Q.pop()
anslst.append(u)
for v in G[u]:
count[v] -= 1
if count[v] == 0:
Q.append(v)
anslst.reverse()
return anslst
v = n
d = [[float('inf')]*n for _ in range(n)]
for i in range(n):
d[i][i] = 0
for x, y in xy:
d[x-1][y-1] = 1
d[y-1][x-1] = 1
for k in range(v):
for i in range(v):
for j in range(v):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
#warshall-floyd
graph = [[] for _ in range(n)]
s = d[a-1]
for x, y in xy:
if s[x-1]+1 == s[y-1]:
graph[y-1].append(x-1)
if s[y-1]+ 1 == s[x-1]:
graph[x-1].append(y-1)
#topological sort
lst = topsort(graph)
#dp
mod = 10**9+7
dp = [0] * n
dp[a-1] = 1
for i in lst:
if i == a-1:
continue
for u in graph[i]:
dp[i] += dp[u]
dp[i] %= mod
print(dp[b-1])