Digits in optimal order P46547


Statement
 

pdf   zip

thehtml

Given two natural numbers m and n, you must construct a number x using the digits {1, …, n} (exactly one of each) such that no (non-empty) prefix of x is a multiple of m. For example, with m=3 and n=4, x=2314 is not a valid order, because 231 is a multiple of 3. In contrast, x=4312 is a valid order, because neither 4, nor 43, nor 431, nor 4312 are multiples of 3.

Moreover, you have a matrix M[1..n][1..n] such that M[i][j] contains the prize that is obtained if digit j is placed immediately to the right of digit i. Maximize the total sum of the prizes.

Input

The input consists of several cases. Each case starts with m and n, followed by M: n rows, each with n natural numbers between 1 and 106, except for the diagonal, that is filled with zeros. You can assume that 3 ≤ m ≤ 1000 and 2 ≤ n ≤ 9.

Output

For each case, print the maximum possible prize. If no x can be constructed, print 0.

Public test cases
  • Input

    10 2
    0 4
    3 0
    
    6 2
    0 1000000
    1 0
    
    3 3
    0 7 7
    7 0 7
    7 7 0
    
    3 4
       0  1  2    3
    1000  0  4 2000
       5  6  0    7
       8  9  1    0
    

    Output

    4
    1
    0
    18
    
  • Information
    Author
    Salvador Roura
    Language
    English
    Translator
    Albert Oliveras
    Original language
    Catalan
    Other languages
    Catalan
    Official solutions
    C++
    User solutions
    C++ Python