package main import ( "fmt" "bufio" "os" "sort" "math" ) type Row struct { row map[int]bool diag map[int]bool cnt int col []int size int } func (this *Row) new(n int) { this.cnt = 0 this.col = make([]int, n) this.size = 0 this.row = make(map[int]bool) this.diag = make(map[int]bool) } func (this *Row) SetCol(A [][]int) { for i := 0; i < len(this.col); i++ { for j, _ := range this.row { if !this.ContainDiag(j, i) { this.col[i] += A[j][i] } } } sort.Ints(this.col) for i := 0; i < len(this.col)-1; i++ { this.col[i+1] += this.col[i] } } func (this *Row) SetDiag(row int, col int) { i := (row << 16) + col if _, ok := this.diag[i]; !ok { this.diag[i] = true } } func (this *Row) ContainDiag(row int, col int) bool { i := (row << 16) + col _, ok := this.diag[i] return ok } func Min(a int, b int) int { if a <= b { return a } else { return b } } func main() { r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) defer w.Flush() var N, M int fmt.Fscan(r, &N, &M) var RowSum []int = make([]int, N) var A [][]int = make([][]int, N) for i := 0; i < N; i++ { A[i] = make([]int, N) sum := 0 for j := 0; j < N; j++ { var a int fmt.Fscan(r, &a) sum += a A[i][j] = a } RowSum[i] = sum } var ans int = math.MaxInt64 for i := 0; i < 1 << (N+2); i++ { row := new(Row) row.new(N) for j := 0; j < N; j++ { if (i & (1 << j)) != 0 { row.cnt += RowSum[j] row.size++ } else { row.row[j] = true } } if (i & (3 << N)) != 0 { for j := 0; j < N; j++ { if _, ok := row.row[j]; ok { if (i & (1 << N)) != 0 { row.cnt += A[j][j] row.SetDiag(j, j) } if (i & (1 << (N+1))) != 0 { if !row.ContainDiag(j, N-1-j) { row.cnt += A[j][N-1-j] row.SetDiag(j, N-1-j) } } } } if (i & (1 << N)) != 0 { row.size++ } if (i & (1 << (N+1))) != 0 { row.size++ } } row.SetCol(A) if row.size == M { ans = Min(ans, row.cnt) } else if (row.size < M && M - row.size <= N) { ans = Min(ans, row.cnt + row.col[M-row.size-1]) } } fmt.Fprintln(w, ans) }