- 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
- 85 lines of Go from the credited upstream file 29D.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 910111213 1415func CF29D(_r io.Reader, _w io.Writer) {16 in := bufio.NewReader(_r)17 out := bufio.NewWriter(_w)18 defer out.Flush()19 20 var n, v, w int21 Fscan(in, &n)22 g := make([][]int, n+1)23 g[1] = append(g[1], 0)24 for i := 1; i < n; i++ {25 Fscan(in, &v, &w)26 g[v] = append(g[v], w)27 g[w] = append(g[w], v)28 }29 l := []int{}30 31 ms := make([]map[int]bool, n+1)32 var f func(v, fa int) map[int]bool33 f = func(v, fa int) map[int]bool {34 ms[v] = map[int]bool{}35 if len(g[v]) == 1 {36 ms[v][v] = true37 Fscan(in, &w)38 l = append(l, w)39 }40 for _, w := range g[v] {41 if w != fa {42 for u := range f(w, v) {43 ms[v][u] = true44 }45 }46 }47 return ms[v]48 }49 f(1, 0)50 51 vs := []int{}52 var f2 func(int, int, []int) bool53 f2 = func(v, fa int, l []int) bool {54 if len(g[v]) == 1 {55 vs = append(vs, v)56 return l[0] == v57 }58 o:59 for len(l) > 0 {60 for _, w := range g[v] {61 if w != fa && ms[w][l[0]] {62 vs = append(vs, v)63 if !f2(w, v, l[:len(ms[w])]) {64 return false65 }66 l = l[len(ms[w]):]67 continue o68 }69 }70 break71 }72 vs = append(vs, v)73 return len(l) == 074 }75 if f2(1, 0, l) {76 for _, v := range vs {77 Fprint(out, v, " ")78 }79 return80 }81 Fprint(out, -1)82}83 8485