Traveling Monk
InterviewTime limit2sMemory limit1024 MB
Given the monk's ascent and descent segments on the same path, find the earliest time both trips put him at the same elevation.
- Level
Medium5 of 10
- Topics
- Binary search, Simulation
- Solved
- No attempts yet
Problem
This puzzle was popularized by Martin Gardner in his book "My Best Mathematical and Logic Puzzles," but it first appeared in the monograph "On Problem-Solving" by the Gestalt psychologist Karl Dunker.
One morning, exactly at sunrise, a Buddhist monk began to climb a tall mountain. The narrow path, no more than a foot or two wide, spiraled around the mountain to a glittering temple at the summit.
The monk ascended the path at varying rates of speed, stopping many times along the way to rest and eat the dried fruit he carried with him. He reached the temple shortly before sunset. After several days of fasting and meditation he began his journey back along the same path, starting at sunrise and again walking at variable speeds with many pauses along the way. His average speed descending was, of course, greater than his average climbing speed.
Prove that there is a spot along the path that the monk will occupy on both trips at precisely the same time of day!
You can probably see why this is true. Can you write a program that computes the time at which the monk will be at the same spot during his ascent and descent?
Input
The input consists of a single test case. The first line contains two integers () and (), the number of segments during the ascent and the number of segments during the descent.
The next lines each contain two integers () and (). is the positive change in elevation the monk gained during that segment, and is the time it took. If the monk rests and eats during a segment, is .
The last lines each contain two integers () and (). is the change in elevation the monk descended during that segment, and is the time it took. If the monk rests and eats during a segment, is .
Output
Output a single floating point number: the earliest point in time at which the monk occupies the same spot during his ascent and his descent. The monk starts both the ascent and the descent at time .
An answer is correct if its absolute or relative error does not exceed .