#P3992. [BJOI2017] 开车

    ID: 2923 远端评测题 1500ms 256MiB 尝试: 0 已通过: 0 难度: 9 上传者: 标签>2017各省省选北京O2优化排序前缀和块状链表,块状数组,分块

[BJOI2017] 开车

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 xy|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 (1in1 \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 41+32=4|4 - 1| + |3 - 2| = 4.

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

Test points Constraints
11 n103n \le 10^3, q=0q = 0
22 n103n \le 10^3, q103q \le 10^3
33 n104n \le 10^4, q104q \le 10^4
44 n5×104n \le 5 \times 10^4, q=0q = 0
565 \sim 6 n3×104n \le 3 \times 10^4, q3×104q \le 3 \times 10^4
7107 \sim 10 n5×104n \le 5 \times 10^4, q5×104q \le 5 \times 10^4

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

Translated by ChatGPT 5