- 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
- 110 lines of Go from the credited upstream file 237E.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 910func cf237E(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const inf int = 1e1813 14 var s string15 var n, lim int16 Fscan(in, &s, &n)17 ns := len(s)18 19 st := 26 + n20 end := st + 121 22 type nb struct{ to, rid, cap, cost int }23 g := make([][]nb, end+1)24 addEdge := func(from, to, cap, cost int) {25 g[from] = append(g[from], nb{to, len(g[to]), cap, cost})26 g[to] = append(g[to], nb{from, len(g[from]) - 1, 0, -cost})27 }28 cnt := [26]int{}29 for _, b := range s {30 cnt[b-'a']++31 }32 for i, c := range cnt {33 addEdge(st, i, c, 0)34 }35 for j := 26; j < 26+n; j++ {36 Fscan(in, &s, &lim)37 cnt = [26]int{}38 for _, b := range s {39 cnt[b-'a']++40 }41 addEdge(j, end, lim, 0)42 for i, c := range cnt {43 addEdge(i, j, c, j-25)44 }45 }46 47 dist := make([]int, len(g))48 type vi struct{ v, i int }49 fa := make([]vi, len(g))50 inQ := make([]bool, len(g))51 spfa := func() bool {52 for i := range dist {53 dist[i] = inf54 }55 dist[st] = 056 inQ[st] = true57 q := []int{st}58 for len(q) > 0 {59 v := q[0]60 q = q[1:]61 inQ[v] = false62 for i, e := range g[v] {63 if e.cap == 0 {64 continue65 }66 w := e.to67 if newD := dist[v] + e.cost; newD < dist[w] {68 dist[w] = newD69 fa[w] = vi{v, i}70 if !inQ[w] {71 inQ[w] = true72 q = append(q, w)73 }74 }75 }76 }77 return dist[end] < inf78 }79 edmondsKarp := func() (maxFlow, minCost int) {80 for spfa() {81 minF := inf82 for v := end; v != st; {83 p := fa[v]84 if c := g[p.v][p.i].cap; c < minF {85 minF = c86 }87 v = p.v88 }89 for v := end; v != st; {90 p := fa[v]91 e := &g[p.v][p.i]92 e.cap -= minF93 g[v][e.rid].cap += minF94 v = p.v95 }96 maxFlow += minF97 minCost += dist[end] * minF98 }99 return100 }101 mf, ans := edmondsKarp()102 if mf < ns {103 Fprint(out, -1)104 } else {105 Fprint(out, ans)106 }107}108 109110