Digits in optimal order P46547


Statement
 

pdf   zip

Given two natural numbers mm and nn, you must construct a number xx using the digits {1,,n}\{1, \dots, n\} (exactly one of each) such that no (non-empty) prefix of xx is a multiple of mm. For example, with m=3m=3 and n=4n=4, x=2314x=2314 is not a valid order, because 231231 is a multiple of 33. In contrast, x=4312x=4312 is a valid order, because neither 44, nor 4343, nor 431431, nor 43124312 are multiples of 33.

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

Input

The input consists of several cases. Each case starts with mm and nn, followed by MM: nn rows, each with nn natural numbers between 1 and 10610^6, except for the diagonal, that is filled with zeros. You can assume that 3m10003 \le m \le 1000 and 2n92 \le n \le 9.

Output

For each case, print the maximum possible prize. If no xx 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