20_regex.py 1.2 KB

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