alex0sunny

ways

Oct 24th, 2021 (edited)
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. MOD = 10 ** 9 + 7
  2.  
  3.  
  4. def get_adjacency_table(edges):
  5.     adjacency_table = {}
  6.     for v, u in edges:
  7.         if v not in adjacency_table:
  8.             adjacency_table[v] = {}
  9.         adjacency_table[v][u] = adjacency_table[v].get(u, 0) + 1
  10.     return adjacency_table
  11.  
  12.  
  13. def traverse(n, adjacency_table, start_vertex, end_vertex):
  14.     planned = {start_vertex}
  15.     visited = set()
  16.     while planned:
  17.         v = planned.pop()
  18.         visited.add(v)
  19.         if v in adjacency_table:
  20.             planned |= set(adjacency_table[v].keys()) - visited
  21.     for v in adjacency_table:
  22.         if v not in visited:
  23.             adjacency_table[v] = {}
  24.         else:
  25.             adjacency_table[v] = {u: c for u, c in adjacency_table[v].items() if u in visited}
  26.     if end_vertex not in visited:
  27.         return 0
  28.     planned = {start_vertex}
  29.     visited = set()
  30.     counters = [0] * (n + 1)
  31.     counters[start_vertex] = 1
  32.     incoming = {}
  33.     for v in adjacency_table:
  34.         for u in adjacency_table[v]:
  35.             if u not in incoming:
  36.                 incoming[u] = set()
  37.             incoming[u].add(v)
  38.     while planned:
  39.         for v in planned:
  40.             if v not in incoming or not incoming[v]:
  41.                 break
  42.         planned.remove(v)
  43.         if v not in visited:
  44.             visited.add(v)
  45.             if v in adjacency_table:
  46.                 for u in adjacency_table[v]:
  47.                     counters[u] = (counters[u] + counters[v] * adjacency_table[v][u]) % MOD
  48.                     if u not in visited and u not in planned:
  49.                         planned.add(u)
  50.                     incoming[u].remove(v)
  51.     return counters[end_vertex]
  52.  
  53.  
  54. n, m = [int(x) for x in input().split()]
  55. edges = [[int(x) for x in input().split()] for _ in range(m)]
  56. start, end = [int(x) for x in input().split()]
  57. table = get_adjacency_table(edges)
  58. print(traverse(n, table, start, end))
  59.  
Add Comment
Please, Sign In to add comment