- 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
- 81 lines of Go from the credited upstream file 1174F.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 "os"7)8 9type (10 input1174 struct {11 n int12 g [][]int13 }14 guess1174 struct{ ans int }15 qIn1174 struct {16 tp string17 v int18 }19 qOut1174 struct{ v int }20)21 2223func CF1174F(in input1174, Q func(qIn1174) qOut1174) (gs guess1174) {24 n, g := in.n, in.g25 type node struct{ d, sz, hson int }26 nodes := make([]node, n+1)27 var f func(v, fa, d int) *node28 f = func(v, fa, d int) *node {29 nodes[v] = node{d, 1, -1}30 o := &nodes[v]31 for _, w := range g[v] {32 if w != fa {33 son := f(w, v, d+1)34 o.sz += son.sz35 if o.hson == -1 || son.sz > nodes[o.hson].sz {36 o.hson = w37 }38 }39 }40 return o41 }42 f(1, 0, 0)43 44 depX := Q(qIn1174{"d", 1}).v45 var f2 func(v int) int46 f2 = func(v int) int {47 hp := []int{v}48 for o := nodes[v]; o.hson != -1; o = nodes[o.hson] {49 hp = append(hp, o.hson)50 }51 end := hp[len(hp)-1]52 depAX := (depX + nodes[end].d - Q(qIn1174{"d", end}).v) / 253 ax := hp[depAX-nodes[v].d]54 if depAX == depX {55 return ax56 }57 return f2(Q(qIn1174{"s", ax}).v)58 }59 gs.ans = f2(1)60 return61}62 63func ioq1174() {64 in := bufio.NewReader(os.Stdin)65 Q := func(q qIn1174) (resp qOut1174) { Println(q.tp, q.v); Fscan(in, &resp.v); return }66 d := input1174{}67 Fscan(in, &d.n)68 g := make([][]int, d.n+1)69 for i := 1; i < d.n; i++ {70 var v, w int71 Fscan(in, &v, &w)72 g[v] = append(g[v], w)73 g[w] = append(g[w], v)74 }75 d.g = g76 gs := CF1174F(d, Q)77 Println("!", gs.ans)78}79 8081