- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 62 lines of Go from the credited upstream file 543C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6 "math/bits"7 "slices"8)9 1011func cf543C(in io.Reader, out io.Writer) {12 var n, m int13 Fscan(in, &n, &m)14 a := make([][]byte, n)15 for i := range a {16 Fscan(in, &a[i])17 }18 19 cost := make([][]int, n)20 rowCost := make([]int, n)21 for i := range cost {22 cost[i] = make([]int, m)23 for j := range cost[i] {24 Fscan(in, &cost[i][j])25 }26 rowCost[i] = slices.Min(cost[i])27 }28 29 type pair struct{ t, cost int }30 colCost := make([][]pair, n)31 for i, s := range a {32 colCost[i] = make([]pair, m)33 for j, b := range s {34 mx := 035 for k, t := range a {36 if t[j] == b {37 colCost[i][j].t |= 1 << k38 colCost[i][j].cost += cost[k][j]39 mx = max(mx, cost[k][j])40 }41 }42 colCost[i][j].cost -= mx43 }44 }45 46 u := 1 << n47 f := make([]int, u)48 for i := 1; i < u; i++ {49 f[i] = 1e950 }51 for s, fs := range f[:u-1] {52 i := bits.TrailingZeros(^uint(s))53 f[s|1<<i] = min(f[s|1<<i], fs+rowCost[i])54 for _, p := range colCost[i] {55 f[s|p.t] = min(f[s|p.t], fs+p.cost)56 }57 }58 Fprint(out, f[u-1])59}60 6162