NOI Contest Archive

Archive / 2025 / Final Round — Day 2

Wizards, Wands, and the Great Tower

Medium · National Olympiad in Informatics 2025 day 2

In a world of magic, there are n young wizards who wish to enter the Great Tower of Sorcery to complete their final trials.
However, the Tower has a rule:

“No wizard may enter without holding a magic wand.”

There are k magic wands scattered along the Ancient Path, a straight road leading directly to the Tower, located at position p.
Each wizard starts at their own position along the path.
To enter the Tower, each wizard must:

  1. First collect exactly one wand (each wand can be taken by only one wizard),
  2. Then proceed to the Tower at position p.

Your mission is to figure out the minimum possible time needed for all wizards to enter the Great Tower with wands.

Input Format

n k p
a1 a2 ... an
b1 b2 ... bk

Output Format

Minimum time for all wizards to enter the Great Tower.

Constraints

- 1 ≤ n ≤ 1000
- n ≤ k ≤ 2000
- 1 ≤ p, a[i], b[j] ≤ 10^9
- No two wizards or wands share the same starting position. But a wand and a wizard can share a same position.

Subtasks

Sample Input 0

3 5 10
1 5 15
2 6 9 13 20

Sample Output 0

9