- 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
- 94 lines of Go from the credited upstream file 120H.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 1011func CF120H(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 genSubStrs := func(s string) []string {17 a := []string{}18 var f func(s, sub string)19 f = func(s, sub string) {20 a = append(a, sub)21 if len(sub) < 4 {22 for i, b := range s {23 f(s[i+1:], sub+string(b))24 }25 }26 }27 f(s, "")28 a = a[1:]29 sort.Strings(a)30 j := 031 for i := 1; i < len(a); i++ {32 if a[j] != a[i] {33 j++34 a[j] = a[i]35 }36 }37 return a[:j+1]38 }39 var n int40 var s string41 Fscan(in, &n)42 sid := map[string]int{}43 strs := []string{}44 g := make([][]int, n)45 for i := range g {46 Fscan(in, &s)47 a := genSubStrs(s)48 for _, s := range a {49 id, ok := sid[s]50 if !ok {51 id = len(sid)52 sid[s] = id53 strs = append(strs, s)54 }55 g[i] = append(g[i], id)56 }57 }58 59 matchL := make([]int, n)60 matchR := make([]int, len(sid))61 for i := range matchR {62 matchR[i] = -163 }64 var used []bool65 var f func(int) bool66 f = func(v int) bool {67 used[v] = true68 for _, w := range g[v] {69 if lv := matchR[w]; lv == -1 || !used[lv] && f(lv) {70 matchR[w] = v71 matchL[v] = w72 return true73 }74 }75 return false76 }77 cnt := 078 for v := range g {79 used = make([]bool, n)80 if f(v) {81 cnt++82 }83 }84 if cnt < n {85 Fprint(out, -1)86 return87 }88 for _, id := range matchL {89 Fprintln(out, strs[id])90 }91}92 9394