- 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
- 112 lines of Go from the credited upstream file 277E.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 "math"7)8 9/*10流量11可以用来“选择”或“计数”。我们可以用 1 单位的流量代表“选择一条边”。12因此,要构成一棵树,我们总共需要选择 n-1 条边,这意味着网络中的总流量应该是 n-1。13 14容量15可以用来施加“约束”。例如,一个节点的出度不能超过 2,就可以通过设置相关边的容量来实现。16 17费用18可以用来衡量“成本”。边的长度自然就是我们想要最小化的成本。19*/20 2122func cf277E(in io.Reader, out io.Writer) {23 var n int24 Fscan(in, &n)25 a := make([]struct{ x, y int }, n)26 for i := range a {27 Fscan(in, &a[i].x, &a[i].y)28 }29 30 S := n * 231 T := S + 132 type nb struct {33 to, rid, cap int34 cost float6435 }36 g := make([][]nb, T+1)37 addEdge := func(from, to, cap int, cost float64) {38 g[from] = append(g[from], nb{to, len(g[to]), cap, cost})39 g[to] = append(g[to], nb{from, len(g[from]) - 1, 0, -cost})40 }41 for i, p := range a {42 addEdge(S, i, 2, 0)43 addEdge(n+i, T, 1, 0)44 for j, q := range a {45 if p.y > q.y {46 addEdge(i, n+j, 1, math.Sqrt(float64((p.x-q.x)*(p.x-q.x)+(p.y-q.y)*(p.y-q.y))))47 }48 }49 }50 51 dis := make([]float64, len(g))52 type vi struct{ v, i int }53 fa := make([]vi, len(g))54 inQ := make([]bool, len(g))55 spfa := func() bool {56 for i := range dis {57 dis[i] = math.MaxFloat6458 }59 dis[S] = 060 inQ[S] = true61 q := []int{S}62 for len(q) > 0 {63 v := q[0]64 q = q[1:]65 inQ[v] = false66 for i, e := range g[v] {67 if e.cap == 0 {68 continue69 }70 w := e.to71 newD := dis[v] + e.cost72 if newD < dis[w] {73 dis[w] = newD74 fa[w] = vi{v, i}75 if !inQ[w] {76 inQ[w] = true77 q = append(q, w)78 }79 }80 }81 }82 return dis[T] < math.MaxFloat6483 }84 maxFlow := 085 minCost := 0.86 for spfa() {87 minF := math.MaxInt88 for v := T; v != S; {89 p := fa[v]90 minF = min(minF, g[p.v][p.i].cap)91 v = p.v92 }93 for v := T; v != S; {94 p := fa[v]95 e := &g[p.v][p.i]96 e.cap -= minF97 g[v][e.rid].cap += minF98 v = p.v99 }100 maxFlow += minF101 minCost += dis[T] * float64(minF)102 }103 104 if maxFlow == n-1 {105 Fprintf(out, "%.6f", minCost)106 } else {107 Fprint(out, -1)108 }109}110 111112