- 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
- 88 lines of Go from the credited upstream file 1305D.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 910func CF1305D() {11 in := bufio.NewReader(os.Stdin)12 var n int13 Fscan(in, &n)14 edges := map[[2]int]bool{}15 for i := 0; i < n-1; i++ {16 var v, w int17 Fscan(in, &v, &w)18 v--19 w--20 edges[[2]int{v, w}] = true21 }22 23 var lca int24 for {25 g := make([][]int, n)26 for e := range edges {27 v, w := e[0], e[1]28 g[v] = append(g[v], w)29 g[w] = append(g[w], v)30 }31 if len(g[lca]) == 0 {32 break33 }34 35 36 var u, maxD int37 var f func(v, fa, d int)38 f = func(v, fa, d int) {39 if d > maxD {40 maxD = d41 u = v42 }43 for _, w := range g[v] {44 if w != fa {45 f(w, v, d+1)46 }47 }48 }49 maxD = -150 f(lca, -1, 0)51 dv := u52 maxD = -153 f(dv, -1, 0)54 dw := u55 Println("?", dv+1, dw+1)56 Fscan(in, &lca)57 lca--58 if lca == dv || lca == dw {59 break60 }61 62 63 var del func(v, end, fa int) bool64 del = func(v, end, fa int) bool {65 if v == end {66 delete(edges, [2]int{v, fa})67 delete(edges, [2]int{fa, v})68 return true69 }70 for _, w := range g[v] {71 if w != fa {72 if del(w, end, v) {73 delete(edges, [2]int{v, w})74 delete(edges, [2]int{w, v})75 return true76 }77 }78 }79 return false80 }81 del(lca, dv, -1)82 del(lca, dw, -1)83 }84 Println("!", lca+1)85}86 8788