Under construction

Still being built. Things may change

To Play or not to Play

Time limit4sMemory limit512 MB

Summary
Given Vasya's and Petya's play intervals and a boost threshold C, find the maximum final experience Vasya can reach when they schedule their play optimally.
Level

Hard9 of 10

Topics
Intervals, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Vasya and Petya are playing an online game. Like most online games, it has a hero progress system where experience makes heroes stronger. Vasya wants to earn as many experience points as possible. If he plays alone, he gets 1 experience point each second. However, if two players play together and their current experience values differ by at most CC points, they can boost their progress, and each of them gets 2 experience points each second.

Vasya and Petya are middle school students, so their parents do not let them play all day. Vasya can only play during the intervals [a1,b1],[a2,b2],…,[an,bn][a_1, b_1], [a_2, b_2], \ldots, [a_n, b_n], and Petya can only play during the intervals [c1,d1],[c2,d2],…,[cm,dm][c_1, d_1], [c_2, d_2], \ldots, [c_m, d_m]. All times are given in seconds from the current moment.

Vasya is good at math. He has noticed that sometimes it can be profitable not to play alone, because the experience difference could become too big, and progress would not be boosted even when they play together.

The two players want a schedule that gives Vasya the greatest possible final experience. Both start with the same experience. Petya does not care much about his own experience, so he is ready to play when needed to maximize Vasya's experience.

Input

The first line contains integers nn, mm, and CC, where nn is the number of intervals when Vasya can play, mm is the number of intervals when Petya can play, and CC is the maximum experience difference that still gives a progress boost when playing together (1≤n,m≤2⋅1051 \le n, m \le 2 \cdot 10^5, 0≤C≤10180 \le C \le 10^{18}).

The next nn lines each contain two integers aia_i and bib_i, an interval when Vasya can play (0≤ai<bi≤10180 \le a_i < b_i \le 10^{18}, bi<ai+1b_i < a_i + 1).

The next mm lines each contain two integers cic_i and did_i, an interval when Petya can play (0≤ci<di≤10180 \le c_i < d_i \le 10^{18}, di<ci+1d_i < c_i + 1).

Output

Print one integer: the maximum experience Vasya can have in the end if both players try to maximize this value.

Examples2

  1. Example 1

    Input
    2 1 5
    1 7
    10 20
    10 20
    
    Expected output
    25
    
  2. Example 2

    Input
    1 2 5
    0 100
    20 60
    85 90
    
    Expected output
    125