Under construction

Still being built. Things may change

Nile

Time limit2sMemory limit1024 MB

Summary
For each query D, find the minimum cost to ship all artifacts when two artifacts share a boat only if their weights differ by at most D.
Level

Hard8 of 10

Topics
Dynamic programming, Sorting, Segment tree
Solved
No attempts yet

Problem

You want to transport NN artifacts through the Nile. The artifacts are numbered from 00 to N−1N - 1. The weight of artifact ii (0≤i<N0 \le i < N) is W[i]W[i].

You use specialized boats to transport the artifacts. Each boat can carry at most two artifacts.

  • If you put a single artifact in a boat, its weight can be arbitrary.
  • If you put two artifacts in the same boat, the boat must be balanced. Specifically, artifacts pp and qq (0≤p<q<N0 \le p < q < N) can share a boat only when their weights differ by at most DD, that is, ∣W[p]−W[q]∣≤D|W[p] - W[q]| \le D.

The cost of transporting artifact ii (0≤i<N0 \le i < N) depends on how many artifacts share its boat:

  • A[i]A[i], if the artifact rides in its own boat.
  • B[i]B[i], if the artifact shares a boat with another artifact.

In the second case, you pay for both artifacts in the boat. If artifacts pp and qq (0≤p<q<N0 \le p < q < N) share a boat, you pay B[p]+B[q]B[p] + B[q].

A boat with a single artifact always costs more than sharing, so B[i]<A[i]B[i] < A[i] for every ii (0≤i<N0 \le i < N).

The river conditions are hard to predict, so the value of DD changes often. Answer QQ questions numbered from 00 to Q−1Q - 1. The questions are given as an array EE of length QQ. The answer to question jj (0≤j<Q0 \le j < Q) is the minimum total cost of transporting all NN artifacts when DD equals E[j]E[j].

Constraints

  • 1≤N≤100 0001 \le N \le 100\,000
  • 1≤Q≤100 0001 \le Q \le 100\,000
  • 1≤W[i]≤1091 \le W[i] \le 10^9 for every ii (0≤i<N0 \le i < N)
  • 1≤B[i]<A[i]≤1091 \le B[i] < A[i] \le 10^9 for every ii (0≤i<N0 \le i < N)
  • 1≤E[j]≤1091 \le E[j] \le 10^9 for every jj (0≤j<Q0 \le j < Q)

Examples1

  1. Example 1

    Input
    1
    5
    10
    3
    1
    1
    
    Expected output
    10