- 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 1027F.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 . "fmt"5 "io"6)7 89func CF1027F(_r io.Reader, out io.Writer) {10 _i, buf := 1<<12, make([]byte, 1<<12)11 rc := func() byte {12 if _i == 1<<12 {13 _r.Read(buf)14 _i = 015 }16 b := buf[_i]17 _i++18 return b19 }20 r := func() (x int) {21 b := rc()22 for ; '0' > b; b = rc() {23 }24 for ; '0' <= b; b = rc() {25 x = x*10 + int(b&15)26 }27 return28 }29 max := func(a, b int) int {30 if b > a {31 return b32 }33 return a34 }35 36 n := r()37 g := make(map[int][]int, n*2)38 for ; n > 0; n-- {39 v, w := r(), r()40 g[v] = append(g[v], w)41 g[w] = append(g[w], v)42 }43 vis := make(map[int]bool, len(g))44 var cntE, cntV, mx, mx2, ans int45 var f func(int)46 f = func(v int) {47 vis[v] = true48 cntV++49 if v > mx {50 mx, mx2 = v, mx51 } else if v > mx2 {52 mx2 = v53 }54 for _, w := range g[v] {55 cntE++56 if !vis[w] {57 f(w)58 }59 }60 }61 for v := range g {62 if !vis[v] {63 cntE, cntV, mx, mx2 = 0, 0, 0, 064 f(v)65 cntE /= 266 if cntE > cntV {67 Fprint(out, -1)68 return69 }70 if cntE == cntV {71 ans = max(ans, mx)72 } else {73 ans = max(ans, mx2)74 }75 }76 }77 Fprint(out, ans)78}79 8081