- 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
- 98 lines of Go from the credited upstream file 1971H.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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)8 910func cf1971H(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 14 var T, n int15o:16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n)18 a := [3][]int{}19 for i := range a {20 a[i] = make([]int, n)21 for j := range a[i] {22 Fscan(in, &a[i][j])23 }24 }25 26 g := make([][]int, n*2)27 addEdge := func(x, a, y, b int) {28 if x < 0 {29 x = -x30 a ^= 131 }32 if y < 0 {33 y = -y34 b ^= 135 }36 v, w := x-1+a*n, y-1+b*n37 g[v] = append(g[v], w)38 }39 for j := 0; j < n; j++ {40 for p := 0; p < 3; p++ {41 for q := 0; q < 3; q++ {42 if q != p {43 addEdge(a[p][j], 0, a[q][j], 1)44 }45 }46 }47 }48 49 sid := make([]int, len(g))50 dfn := make([]int, len(g))51 clock := 052 st := []int{}53 inSt := make([]bool, len(g))54 var tarjan func(int) int55 tarjan = func(v int) int {56 clock++57 dfn[v] = clock58 lowV := clock59 st = append(st, v)60 inSt[v] = true61 for _, w := range g[v] {62 if dfn[w] == 0 {63 lowW := tarjan(w)64 lowV = min(lowV, lowW)65 } else if inSt[w] {66 lowV = min(lowV, dfn[w])67 }68 }69 if dfn[v] == lowV {70 for {71 w := st[len(st)-1]72 st = st[:len(st)-1]73 inSt[w] = false74 sid[w] = v75 if w == v {76 break77 }78 }79 }80 return lowV81 }82 for i, ts := range dfn {83 if ts == 0 {84 tarjan(i)85 }86 }87 for i, id := range sid[:n] {88 if id == sid[i+n] {89 Fprintln(out, "NO")90 continue o91 }92 }93 Fprintln(out, "YES")94 }95}96 9798