This page is still under construction.

Parts of this page are still being built. What you see may change.

Umbrellas for Cows

Interview

Time limit1sMemory limit128 MB

Summary
Given cow positions on a line and a price for each umbrella width, find the cheapest set of umbrellas that covers every cow, allowing overlaps.
Level

Medium6 of 10

Topics
Dynamic programming, Sorting, Prefix sum, Greedy
Solved
No attempts yet

Problem

It is a rainy day. Farmer John's NN (1≤N≤5,0001 \le N \le 5{,}000) cows, numbered 1…N1 \ldots N, do not like getting wet. The cows stand in roofless stalls arranged along a number line. The stalls occupy the integer coordinates from 11 to MM (1≤M≤100,0001 \le M \le 100{,}000). Cow ii stands at coordinate XiX_i (1≤Xi≤M1 \le X_i \le M), and no two cows share a stall.

To keep the cows dry, Farmer John wants to buy umbrellas. An umbrella that spans coordinates XiX_i to XjX_j (with Xi≤XjX_i \le X_j) has width Xj−Xi+1X_j - X_i + 1. An umbrella of width WW costs CWC_W (1≤CW≤1,000,0001 \le C_W \le 1{,}000{,}000). A wider umbrella is not necessarily more expensive than a narrower one.

Find the minimum total cost of a set of umbrellas that keeps every cow dry. In an optimal solution the umbrellas may overlap.

Input

  • The first line contains two space-separated integers NN and MM.
  • Each of the next NN lines contains one integer XiX_i.
  • Each of the following MM lines contains one integer; the jj-th of these lines is CjC_j, the cost of an umbrella of width jj.

Output

  • Print a single integer: the minimum cost required to buy umbrellas that keep all cows dry.

Hint

There are 1212 stalls, and cows occupy stalls 11, 22, 44, 88, 1111, and 1212. An umbrella covering one stall costs 22, one covering two stalls costs 33, and so on.

By buying a width-44 umbrella, a width-11 umbrella, and a width-22 umbrella, all cows can be covered for a total cost of 4+2+3=94 + 2 + 3 = 9:

UUUUUUUUUU           U        UUUU
C  C     C           C        C  C
|--|--|--|--|--|--|--|--|--|--|--|
1  2  3  4  5  6  7  8  9  10 11 12

Here C marks a cow and U marks part of an umbrella.

Examples1

  1. Example 1

    Input
    6 12
    1
    2
    11
    8
    4
    12
    2
    3
    4
    4
    8
    9
    15
    16
    17
    18
    19
    19
    
    Expected output
    9