20_regex.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. import sys
  3. from heapq import heapify, 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. inf = 1 << 32
  27. dist = {v: inf for v in graph}
  28. dist[source] = 0
  29. Q = [(dist[v], v) for v in graph]
  30. heapify(Q)
  31. while Q:
  32. udist, u = heappop(Q)
  33. if udist == dist[u]:
  34. for v in graph[u]:
  35. alt = udist + 1
  36. if alt < dist[v]:
  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()))