## Rated Contest 2 P4 - Ski Lifts

View as PDF

Points: 12 (partial)
Time limit: 2.0s
PyPy 3 5.0s
Memory limit: 256M

Author:
Problem types

Daniel and his friends are geared up and ready to ski, so they exit the lodge and behold the breathtaking mountains of snow before them. The ski resort is renowned for its towering mountains, whose majestic peaks disappear into the ethereal clouds and are said to touch the heavens.

In fact, one ride up on a ski lift can take as long as minutes! That's even longer than the Peak2Peak Gondola (located in Whistler, British Columbia), the longest ski lift in the real world, which lasts minutes.

There are ski lifts in the resort, with the -th ski lift taking minutes to go one way. Each ski lift only has one cart, which will travel from the bottom to the top, then from the top to the bottom, turning around immediately after reaching either end.

Right now it's 9am, and the cart on the -th lift initially starts at minutes way up—heading either up or down. If is , then the lift is minutes up the ride and is travelling upwards, and if is , the lift is minutes up the ride and is travelling downwards. Note that if is either or , the direction does not matter.

Daniel, being the analytical and careful-planning type, will ask questions to plan his skiing itinerary, each of which asks: Given minutes past 9am, how long must he wait for a ski lift to arrive at the top or bottom of its path? If is , he wants to know how long it takes for any ski lift to reach the bottom of its path, and if is , he wants to know how long it takes for any ski lift to reach the top of its path.

#### Constraints

$$d_i, s_i ∈ \{1, 2\}$$

#### Input Specifications

The first line contains two integers, and .

The next lines contain three integers each, representing , , and .

The next lines contain two integers each, representing and .

#### Output Specifications

For each question, output the time from , in minutes, for any ski lift to reach the bottom (for ) or the top (for ) of its path.

#### Sample Input 1

2 4
4 2 1
7 1 2
4 2
6 1
13 2
3 2

#### Sample Output 1

4
0
5
5

#### Sample Explanation 1

Query Explanation Result
1 The first lift reaches the top at , then the bottom at , before reaching the top again at . The second lift reaches the bottom at , then the top at . Earliest time a lift arrives is ,
2 The first lift reaches the top at , then the bottom at . The second lift reaches the bottom at , then the top at , before reaching the bottom again at .
3 The first lift reaches the top at . The second lift reaches the top at

The last query was calculated similarly.