- 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
- 94 lines of Go from the credited upstream file 1437C.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 CF1437C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 const inf int = 1e915 abs := func(x int) int {16 if x < 0 {17 return -x18 }19 return x20 }21 22 var T, n, t int23 for Fscan(in, &T); T > 0; T-- {24 Fscan(in, &n)25 type nb struct{ to, rid, cap, cost int }26 g := make([][]nb, 3*n+2)27 addEdge := func(from, to, cap, cost int) {28 g[from] = append(g[from], nb{to, len(g[to]), cap, cost})29 g[to] = append(g[to], nb{from, len(g[from]) - 1, 0, -cost})30 }31 st, end := 0, 3*n+132 for i := 1; i <= n; i++ {33 addEdge(st, i, 1, 0)34 }35 for i := n + 1; i <= 3*n; i++ {36 addEdge(i, end, 1, 0)37 }38 for i := 1; i <= n; i++ {39 Fscan(in, &t)40 for j := 1; j <= 2*n; j++ {41 addEdge(i, n+j, inf, abs(t-j))42 }43 }44 45 n = 3*n + 246 dist := make([]int, n)47 type pair struct{ v, i int }48 fa := make([]pair, n)49 spfa := func() bool {50 for i := range dist {51 dist[i] = inf52 }53 dist[st] = 054 inQ := make([]bool, n)55 inQ[st] = true56 q := []int{st}57 for len(q) > 0 {58 v := q[0]59 q = q[1:]60 inQ[v] = false61 for i, e := range g[v] {62 if e.cap == 0 {63 continue64 }65 w := e.to66 if newD := dist[v] + e.cost; newD < dist[w] {67 dist[w] = newD68 fa[w] = pair{v, i}69 if !inQ[w] {70 q = append(q, w)71 inQ[w] = true72 }73 }74 }75 }76 return dist[end] < inf77 }78 minCost := 079 for spfa() {80 for v := end; v != st; {81 p := fa[v]82 e := &g[p.v][p.i]83 e.cap--84 g[v][e.rid].cap++85 v = p.v86 }87 minCost += dist[end]88 }89 Fprintln(out, minCost)90 }91}92 9394