06_boatrace.py 723 B

12345678910111213141516171819
  1. #!/usr/bin/env python3
  2. import sys
  3. import re
  4. from functools import reduce
  5. from math import ceil, sqrt
  6. from operator import mul
  7. def wins(time, distance):
  8. # invariant: hold * (time - hold) > distance
  9. # solve: -hold^2 + time*hold - distance = 0
  10. # hold = (time +- sqrt(time^2 - 4 * distance)) / 2
  11. # = (time +- d) / 2
  12. # solution: (time - d) / 2 < hold < (time + d) / 2
  13. d = sqrt(time ** 2 - 4 * distance)
  14. return int((time + d) / 2) - ceil((time - d) / 2) + 1 - 2 * (d % 1 == 0)
  15. times, distances = (re.findall(r'\d+', line) for line in sys.stdin)
  16. print(reduce(mul, (wins(int(t), int(d)) for t, d in zip(times, distances))))
  17. print(wins(int(''.join(times)), int(''.join(distances))))