#P1798. 小明搬家

小明搬家

Description

Xiaoming is moving, and everyone comes to help.

Xiaoming now lives on floor NN. In total, KK people need to carry MM large boxes up to floor NN.

At the start, all MM boxes are on floor 11. After a period of chaotic moving, things got messy. Everyone then realized the chaos was inefficient and agreed on a more efficient method:

  • Each person moves at a speed of one floor per minute, either up or down.
  • Everyone going up carries exactly one box; everyone going down carries no box.
  • Upon reaching floor NN, a person immediately puts the box down and starts going down. Upon reaching floor 11, a person immediately picks up a box and starts going up.
  • When a person going up meets a person going down on the stairs, the up-going person hands the box to the other person, and both reverse direction simultaneously. That is, the person who was carrying a box upward now goes downward without a box, and the person who was going downward without a box now goes upward carrying the box.

Find the minimum time needed to finish moving all the boxes.

Input Format

The first line contains N,K,MN, K, M, denoting the number of floors, the number of people, and the number of boxes still lying on floor 11.

The next KK lines each contain two integers Ai,BiA_i, B_i.

AiA_i is the current floor of the ii-th person. BiB_i is 00 or 11: 00 means the ii-th person is carrying a box and going up, and 11 means the ii-th person is going down without a box.

It is guaranteed that no two people are on the same floor at the same time; anyone on floor 11 must be going up with a box, and anyone on floor NN must be going down without a box.

Output Format

Output a single integer: the time to finish moving all the boxes.

5 2 4
1 0
3 0

20

Hint

  • For 30%30\% of the testdata, K100K \leq 100, M100M \leq 100.
  • For 60%60\% of the testdata, K1000K \leq 1000, M109M \leq 10^9.
  • For 100%100\% of the testdata, N109N \le 10^9, K5×105K \le 5 \times 10^5, M109M \le 10^9.

Translated by ChatGPT 5