Package Pickup

시간 제한4초메모리 제한2048 MB

요약
소들이 M 간격의 등차수열 위치에 있고 소포도 같은 간격으로 놓여 있을 때, 모든 소포를 줍는 데 필요한 최소 총 이동 시간을 구한다.
난이도

어려움10점 중 9점

유형
그리디, 수학, 정렬, 누적 합
정답자
아직 제출이 없습니다

문제

Farmer John has distributed cows and packages in a weird pattern across the number line using the following process:

  • Farmer John chooses a number MM (1≤M≤10181 \le M \le 10^{18}).
  • Farmer John chooses NN (1≤N≤2⋅104)1 \le N \le 2 \cdot 10^4) intervals \[L_i,R_i]\[L\_i, R\_i] to distribute cows in (1≤L_i≤R_i≤10181 \le L\_i \le R\_i \le 10^{18}). He then places cows at locations L_i,L_i+M,L_i+2M,…,R_iL\_i, L\_i + M, L\_i + 2M, \ldots, R\_i. It is guaranteed that R_i−L_iR\_i - L\_i is a multiple of MM.
  • Farmer John chooses PP (1≤P≤2⋅104)1 \le P \le 2 \cdot 10^4) intervals \[A_i,B_i]\[A\_i, B\_i] to distribute packages in (1≤A_i≤B_i≤10181 \le A\_i \le B\_i \le 10^{18}). He then places packages at locations A_i,A_i+M,A_i+2M,…,B_iA\_i, A\_i + M, A\_i + 2M, \ldots, B\_i. It is guaranteed that B_i−A_iB\_i - A\_i is a multiple of MM.

Once the cows and packages are distributed, Farmer John wants to see how long it takes the cows to pick up the packages. Every second, Farmer John can issue a command to a single cow to move one unit left or right of their current position with his handy walkie talkie. If a cow travels to the position where a package is located, they are able to pick it up. Farmer John wants to know the minimum time in seconds that it would take the cows to pick up every package.

입력

The first line contains MM, NN, and PP.

The next NN lines each contain two integers L_iL\_i and R_iR\_i.

The next PP lines each contain two integers A_iA\_i and B_iB\_i.

출력

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.

예제2

  1. 예제 1

    입력
    100 3 7
    10 10
    20 20
    30 30
    7 7
    11 11
    13 13
    17 17
    24 24
    26 26
    33 33
    
    예상 출력
    22
    
  2. 예제 2

    입력
    2 1 1
    1 5
    2 6
    
    예상 출력
    3