80 likes | 201 Views
Quest for the Polar Bear. Ivan Li. Statistics. 42. #Max = 9 Mean (attempted) = 39.4. Problem. A car travels to the South If it reaches a road, follow its direction Find the number of roads visited. Something you must know. The travel direction is S, E or W Cannot go North!
E N D
Quest for the Polar Bear Ivan Li
Statistics 42 • #Max = 9 • Mean (attempted) = 39.4
Problem • A car travels to the South • If it reaches a road, follow its direction • Find the number of roads visited
Something you must know • The travel direction is S, E or W • Cannot go North! • There are polar bears in the South • In zoos =]
Observations • Whether a car will reach a road on the south depends on the x coordinates of the car and the start and end points of the road • (x1 ≤ x and x ≤ x2) or (x2 ≤ x and x ≤ x1) • (x1-x)*(x2-x) ≤ 0 • Cool but risky =] • After the car finishes travelling on a road, its position is in the end point
Be Naive • For each road, check if the car will hit it if the car go straight • Road on the south of the car? • Check x coordinates? • If it will, calculate the time (difference in y coordinates) the car will hit the road • Then go hit the road with min time! • Repeat the process until the car hit no roads • O(n2)
Important Observations • After the car has passed a road • i.e. y coordinates of car smaller than road • Then we can ignore the road sayonara!!! • When the car has y coordinate equals that of a road • Hit or miss • Hit: change the position of the car, bye to the road • Miss: Just bye to the road • The y coordinates of the car won’t increase • The car must visit the roads in y order • The input is sorted!
Full Solution • Keep the index of the last road not passed • Hit or Miss? • Increment the index • Complexity O(n)