#P3992. [BJOI2017] 开车

    ID: 4703 远端评测题 1500ms 256MiB 尝试: 1 已通过: 0 显示难度NOI/NOI+/CTS 上传者: 标签>2017各省省选北京O2优化排序前缀和分块

[BJOI2017] 开车

Problem Description

There are nn cars located at positions a1,a2,…,ana_1, a_2, \ldots, a_n, and nn gas stations located at positions b1,b2,…,bnb_1, b_2, \ldots, b_n.

Each gas station can serve at most one car, so you must drive the cars to distinct gas stations. The cost for a car to drive from position xx to position yy is ∣x−y∣|x - y|. Find an assignment that minimizes the sum of costs.

You are also given qq operations. In each operation, the position of the ii-th car is updated to xx. After each update, you need to output the minimal total cost of an optimal assignment.

Input Format

The first line contains a positive integer nn.

The second line contains nn integers a1,a2,…,ana_1, a_2, \ldots, a_n.

The third line contains nn integers b1,b2,…,bnb_1, b_2, \ldots, b_n.

The fourth line contains a positive integer qq, the number of operations.

Each of the next qq lines contains two integers ii (1≤i≤n1 \le i \le n) and xx, indicating that the position of car ii is updated to xx.

All car and gas station positions are always within 00 to 10910^9.

Output Format

Output q+1q + 1 lines. The first line is the minimal total cost before any operations.

Then output qq lines, where the ii-th line is the minimal total cost after operation ii.

2
1 2
3 4
1
1 3

4
2

Hint

Sample explanation:

Initially, drive the first car to position 44 and the second car to position 33, with a total cost of ∣4−1∣+∣3−2∣=4|4 - 1| + |3 - 2| = 4.

After the update, the first car’s position becomes 33, and the total cost is ∣3−3∣+∣4−2∣=2|3 - 3| + |4 - 2| = 2.

Test points Constraints
11 n≤103n \le 10^3, q=0q = 0
22 n≤103n \le 10^3, q≤103q \le 10^3
33 n≤104n \le 10^4, q≤104q \le 10^4
44 n≤5×104n \le 5 \times 10^4, q=0q = 0
5∼65 \sim 6 n≤3×104n \le 3 \times 10^4, q≤3×104q \le 3 \times 10^4
7∼107 \sim 10 n≤5×104n \le 5 \times 10^4, q≤5×104q \le 5 \times 10^4

For 100%100\% of the testdata, 1≤n≤5×1041 \le n \le 5 \times 10^4, 0≤q≤5×1040 \le q \le 5 \times 10^4.

Translated by ChatGPT 5