
USACO 2025 US Open Contest, Platinum
Problem 3. Package Pickup
Contest has ended.

Log in to allow submissions in analysis mode
**Note: The time limit for this problem is 4s, 2x the default.**
Farmer John has distributed cows and packages in a weird pattern across the number line using the following process:
- Farmer John chooses a number M (1≤M≤1018).
- Farmer John chooses N (1≤N≤2⋅104) intervals [Li,Ri] to distribute cows in (1≤Li≤Ri≤1018). He then places cows at locations Li,Li+M,Li+2M,…,Ri. It is guaranteed that Ri−Li is a multiple of M.
- Farmer John chooses P (1≤P≤2⋅104) intervals [Ai,Bi] to distribute packages in (1≤Ai≤Bi≤1018). He then places packages at locations Ai,Ai+M,Ai+2M,…,Bi. It is guaranteed that Bi−Ai is a multiple of M.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains M, N, and P.
The next N lines each contain two integers Li and Ri.
The next P lines each contain two integers Ai and Bi.
OUTPUT FORMAT (print output to the terminal / stdout):
Output a single integer, representing the minimum amount of time it can take the cows to pick up all the packages, given that every second, he can issue a single left/right command to a single cow.SAMPLE INPUT:
100 3 7 10 10 20 20 30 30 7 7 11 11 13 13 17 17 24 24 26 26 33 33
SAMPLE OUTPUT:
22In the above test case, suppose the cows and packages are numbered from left to right. Farmer John can follow this procedure to pick up the packages in 22 seconds:
- Issue 3 lefts to cow 1 so that it picks up package 1
- Issue 3 rights to cow 3 so that it picks up package 7
- Issue 4 rights to cow 2 so that it picks up package 5
- Issue 10 rights to cow 1 so that it picks up packages 2, 3, and 4
- Issue 2 rights to cow 2 so that it picks up package 6
SAMPLE INPUT:
2 1 1 1 5 2 6
SAMPLE OUTPUT:
3
There are three cows and three packages. Farmer John can issue one right to each cow.
SCORING:
- Input 3-4: It is guaranteed that the total number of cows and packages does not exceed 2⋅105
- Inputs 5-10: It is guaranteed that N,P≤500.
- Inputs 11-13: It is guaranteed that no intervals of packages or cows intersect.
- Inputs 14-20: No additional constraints.
Problem credits: Suhas Nagar and Benjamin Qi