- 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 1907G.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)8 910func cf1907G(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n int16 var s []byte17o:18 for Fscan(in, &T); T > 0; T-- {19 Fscan(in, &n, &s)20 g := make([]int, n)21 deg := make([]int, n)22 for i := range g {23 Fscan(in, &g[i])24 g[i]--25 deg[g[i]]++26 }27 28 ans := []int{}29 q := []int{}30 for i, d := range deg {31 if d == 0 {32 q = append(q, i)33 }34 }35 for len(q) > 0 {36 v := q[0]37 q = q[1:]38 w := g[v]39 if s[v] == '1' {40 ans = append(ans, v)41 s[w] ^= 142 }43 if deg[w]--; deg[w] == 0 {44 q = append(q, w)45 }46 }47 48 for i, d := range deg {49 if d == 0 {50 continue51 }52 ring := []int{i}53 p1 := []int{}54 if s[i] == '1' {55 p1 = append(p1, 0)56 }57 for v := g[i]; v != i; v = g[v] {58 deg[v] = 059 if s[v] == '1' {60 p1 = append(p1, len(ring))61 }62 ring = append(ring, v)63 }64 if len(p1) == 0 {65 continue66 }67 if len(p1)%2 > 0 {68 Fprintln(out, -1)69 continue o70 }71 72 cnt := 073 for i := 1; i < len(p1); i += 2 {74 cnt += p1[i] - p1[i-1]75 }76 idx := p1[0]77 if cnt > len(ring)-cnt {78 idx = p1[1]79 }80 81 ring = append(ring[idx:], ring[:idx]...)82 for j, v := range ring {83 if s[v] == '1' {84 ans = append(ans, v)85 s[ring[(j+1)%len(ring)]] ^= 186 }87 }88 }89 Fprintln(out, len(ans))90 for _, v := range ans {91 Fprint(out, v+1, " ")92 }93 Fprintln(out)94 }95}96 9798