- 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
- 93 lines of Go from the credited upstream file 954F.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 "bufio"5 . "fmt"6 "io"7 "sort"8)9 1011type matrix54 [][]int6412 13func newMatrix54(n, m int) matrix54 {14 a := make(matrix54, n)15 for i := range a {16 a[i] = make([]int64, m)17 }18 return a19}20 21func newIdentityMatrix54(n int) matrix54 {22 a := make(matrix54, n)23 for i := range a {24 a[i] = make([]int64, n)25 a[i][i] = 126 }27 return a28}29 30func (a matrix54) mul(b matrix54) matrix54 {31 c := newMatrix54(len(a), len(b[0]))32 for i, row := range a {33 for j := range b[0] {34 for k, v := range row {35 c[i][j] = (c[i][j] + v*b[k][j]) % (1e9 + 7)36 }37 }38 }39 return c40}41 42func CF954F(_r io.Reader, _w io.Writer) {43 in := bufio.NewReader(_r)44 out := bufio.NewWriter(_w)45 defer out.Flush()46 47 var n, row int48 var m, l, r int6449 Fscan(in, &n, &m)50 type pair struct {51 row int52 col int6453 delta int854 }55 block := make([]pair, 0, n*2+2)56 block = append(block, pair{0, 2, 0}, pair{0, m + 1, 0})57 for ; n > 0; n-- {58 Fscan(in, &row, &l, &r)59 row--60 block = append(block, pair{row, l, 1}, pair{row, r + 1, -1})61 }62 sort.Slice(block, func(i, j int) bool { return block[i].col < block[j].col })63 64 ans := newIdentityMatrix54(3)65 cntB := [3]int{}66 for i, b := range block[:len(block)-1] {67 cntB[b.row] += int(b.delta)68 m := newMatrix54(3, 3)69 if cntB[0] == 0 {70 m[0][0] = 171 m[1][0] = 172 }73 if cntB[1] == 0 {74 m[0][1] = 175 m[1][1] = 176 m[2][1] = 177 }78 if cntB[2] == 0 {79 m[1][2] = 180 m[2][2] = 181 }82 for n := block[i+1].col - b.col; n > 0; n >>= 1 {83 if n&1 > 0 {84 ans = ans.mul(m)85 }86 m = m.mul(m)87 }88 }89 Fprint(out, ans[1][1])90}91 9293