#P2769. 猴子上树

猴子上树

Description

In Monkey Village, there is a straight mountain path that is very narrow, and its width can be ignored. There are nn monkeys standing on the path watching the students who came to compete today. Let a positive integer XiX_i denote the position of the ii-th monkey; no two monkeys stand at the same position. There are mm tall trees planted at positions along this path. Let a positive integer YjY_j denote the position of the jj-th tree; no two trees occupy the same position.

While the monkeys were intently admiring everyone's excellent programming skills, a tiger swaggered over. The monkeys broke into a cold sweat. Their first reaction was to find a tall tree to climb, which would help them avoid being bitten or eaten by the tiger (do not consider the tiger climbing trees).

If the monkey at position aa runs to the tree at position bb, the energy cost is ab|a - b|. To make the most effective use of these trees for shelter, each tree must have at least one monkey. Please compute the minimum total energy required for all nn monkeys to climb onto trees.

Input Format

The input consists of 4 lines.

  • Line 1: an integer nn, the number of monkeys.
  • Line 2: nn integers; the ii-th integer XiX_i is the position of the ii-th monkey.
  • Line 3: an integer mm, the number of trees.
  • Line 4: mm integers; the jj-th integer is the position YjY_j of the jj-th tree.

Output Format

Output one line with a single integer: the minimum total energy required for all nn monkeys to climb onto trees.

3
1 4 5
2
3 8

6

3
3 1 10
2
8 3

4

Hint

For 30%30\% of the testdata, 1n5001 \le n \le 500, 1Xi,Yi1051 \le X_i, Y_i \le 10^5.

For 100%100\% of the testdata, 1n50001 \le n \le 5000, 1mn1 \le m \le n, 1Xi,Yi1091 \le X_i, Y_i \le 10^9.

Translated by ChatGPT 5