20_regex.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. import sys
  3. from heapq import heappush, heappop
  4. def parse(regex):
  5. graph = {}
  6. branches = []
  7. dirs = {'N': (0, -1), 'W': (-1, 0), 'S': (0, 1), 'E': (1, 0)}
  8. cur = (0, 0)
  9. assert regex[0] == '^' and regex[-1] == '$'
  10. for c in regex[1:-1]:
  11. if c == '(':
  12. branches.append(cur)
  13. elif c == ')':
  14. cur = branches.pop()
  15. elif c == '|':
  16. cur = branches[-1]
  17. else:
  18. dx, dy = dirs[c]
  19. x, y = cur
  20. vertex = x + dx, y + dy
  21. graph.setdefault(cur, []).append(vertex)
  22. graph.setdefault(vertex, []).append(cur)
  23. cur = vertex
  24. return graph
  25. def shortest_paths(graph, source):
  26. dist = {source: 0}
  27. Q = [(0, source)]
  28. visited = {source}
  29. while Q:
  30. udist, u = heappop(Q)
  31. for v in graph[u]:
  32. if v not in visited:
  33. visited.add(v)
  34. alt = udist + 1
  35. known = dist.get(v, None)
  36. if known is None or alt < known:
  37. dist[v] = alt
  38. heappush(Q, (alt, v))
  39. return dist
  40. regex = sys.stdin.readline().rstrip()
  41. graph = parse(regex)
  42. dist = shortest_paths(graph, (0, 0))
  43. print(max(dist.values()))
  44. print(sum(int(d >= 1000) for d in dist.values()))