Under construction

Still being built. Things may change

Minimum-Cost Prefix-Free Language

Time limit1sMemory limit128 MB

Summary
Given n and d character costs, find the minimum total cost of a prefix-free set of exactly n words; multiple test cases end with 0 0.
Level

Hard8 of 10

Topics
Dynamic programming, Greedy, Tree, Combinatorics
Solved
No attempts yet

Problem

You must build a language of nn words over an alphabet of dd characters c1,c2,…,cdc_1, c_2, \ldots, c_d. The language must be prefix-free: no word may be a prefix of another, i.e. there is no pair of words (s,t)(s, t) in which ss is a prefix of tt.

Each character cic_i has a usage cost wiw_i. The cost of a word equals the sum of the costs of its characters. For example, if c1=ac_1 = a, c2=bc_2 = b, w1=1w_1 = 1, and w2=10w_2 = 10, then the cost of the word aba is 1+10+1=121 + 10 + 1 = 12.

The cost of a language equals the sum of the costs of all its words. For example, the language ab, bbb, baaa costs 11+30+13=5411 + 30 + 13 = 54.

Among all prefix-free languages that contain exactly nn words, find the minimum possible total cost.

When n=1n = 1, the single word may be the empty word, whose cost is 00.

Input

The input contains several test cases. Each test case begins with a line holding two integers nn and dd (1≤n≤2001 \le n \le 200, 1≤d≤2001 \le d \le 200). The next line holds dd nonnegative integers w1,w2,…,wdw_1, w_2, \ldots, w_d. The input ends with a line containing two zeros, which is not a test case.

Output

For each test case, output a single line with the minimum cost of a prefix-free language of nn words built from the given dd characters.

Examples3

  1. Example 1

    Input
    3 4
    1 10 100 1000
    0 0
    
    Expected output
    23
    
  2. Example 2

    Input
    1 5
    7 3 9 2 6
    0 0
    
    Expected output
    0
    
  3. Example 3

    Input
    3 2
    1 5
    0 0
    
    Expected output
    13