- 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
- 100 lines of Go from the credited upstream file 1777E.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 "io"7 "sort"8)9 1011func CF1777E(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 min := func(a, b int) int {16 if a > b {17 return b18 }19 return a20 }21 22 var T, n, m, v, w int23 for Fscan(in, &T); T > 0; T-- {24 Fscan(in, &n, &m)25 type nb struct{ to, wt int }26 g := make([][]nb, n)27 wt := make([]int, m+1)28 for i := 1; i <= m; i++ {29 Fscan(in, &v, &w, &wt[i])30 v--31 w--32 g[v] = append(g[v], nb{w, 0})33 g[w] = append(g[w], nb{v, wt[i]})34 }35 sort.Ints(wt)36 i := sort.Search(m+1, func(i int) bool {37 limit := wt[i]38 dfn := make([]int, n)39 dfsClock := 040 stk := []int{}41 inStk := make([]bool, n)42 last := 043 var f func(int) int44 f = func(v int) int {45 dfsClock++46 dfn[v] = dfsClock47 lowV := dfsClock48 stk = append(stk, v)49 inStk[v] = true50 for _, e := range g[v] {51 if e.wt > limit {52 continue53 }54 if w := e.to; dfn[w] == 0 {55 lowV = min(lowV, f(w))56 } else if inStk[w] {57 lowV = min(lowV, dfn[w])58 }59 }60 if dfn[v] == lowV {61 for {62 last, stk = stk[len(stk)-1], stk[:len(stk)-1]63 inStk[last] = false64 if last == v {65 break66 }67 }68 }69 return lowV70 }71 for v, t := range dfn {72 if t == 0 {73 f(v)74 }75 }76 vis := make([]bool, n)77 left := n78 var f2 func(int)79 f2 = func(v int) {80 vis[v] = true81 left--82 for _, e := range g[v] {83 if e.wt <= limit && !vis[e.to] {84 f2(e.to)85 }86 }87 }88 f2(last)89 return left == 090 })91 if i > m {92 Fprintln(out, -1)93 } else {94 Fprintln(out, wt[i])95 }96 }97}98 99100