- 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 1476E.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 CF1476E(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, m, k, v int16 Fscan(in, &n, &m, &k)17 mp := make(map[string]int, n)18 for i := 1; i <= n; i++ {19 var s string20 Fscan(in, &s)21 mp[s] = i22 }23 24 var s []byte25 var ids []int26 var f func(int)27 f = func(p int) {28 if p == k {29 if id := mp[string(s)]; id > 0 {30 ids = append(ids, id-1)31 }32 return33 }34 f(p + 1)35 tmp := s[p]36 s[p] = '_'37 f(p + 1)38 s[p] = tmp39 }40 41 g := make([][]int, n)42 deg := make([]int, n)43o:44 for i := 0; i < m; i++ {45 Fscan(in, &s, &v)46 v--47 ids = []int{}48 f(0)49 for _, id := range ids {50 if id == v {51 for _, w := range ids {52 if w != v {53 g[v] = append(g[v], w)54 deg[w]++55 }56 }57 continue o58 }59 }60 Fprintln(out, "NO")61 return62 }63 64 ans := []int{}65 q := []int{}66 for i, d := range deg {67 if d == 0 {68 q = append(q, i)69 }70 }71 for len(q) > 0 {72 v := q[0]73 q = q[1:]74 ans = append(ans, v)75 for _, w := range g[v] {76 if deg[w]--; deg[w] == 0 {77 q = append(q, w)78 }79 }80 }81 82 if len(ans) < n {83 Fprint(out, "NO")84 return85 }86 Fprintln(out, "YES")87 for _, v := range ans {88 Fprint(out, v+1, " ")89 }90}91 9293