- 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
- 104 lines of Go from the credited upstream file 1245D.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 "math"8)9 1011func CF1245D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 abs := func(x int) int {16 if x < 0 {17 return -x18 }19 return x20 }21 22 var n int23 Fscan(in, &n)24 type pair struct{ x, y int }25 city := make([]pair, n)26 for i := range city {27 Fscan(in, &city[i].x, &city[i].y)28 }29 cityCost := make([]int, n)30 for i := range cityCost {31 Fscan(in, &cityCost[i])32 }33 wireCost := make([]int, n)34 for i := range wireCost {35 Fscan(in, &wireCost[i])36 }37 38 39 dis := make([][]int64, n+1)40 for i := range dis {41 dis[i] = make([]int64, n+1)42 }43 for i, c := range cityCost {44 dis[i][n] = int64(c) 45 dis[n][i] = int64(c)46 for j := i + 1; j < n; j++ {47 48 dis[i][j] = int64(abs(city[i].x-city[j].x)+abs(city[i].y-city[j].y)) * int64(wireCost[i]+wireCost[j])49 dis[j][i] = dis[i][j]50 }51 }52 53 totCost := int64(0)54 ansCity := []interface{}{}55 ansWire := []pair{}56 57 58 type pair2 struct {59 cost int6460 v int61 }62 minCost := make([]pair2, n+1)63 for i := range minCost {64 minCost[i].cost = math.MaxInt6465 }66 minCost[0].cost = 067 used := make([]bool, n+1)68 for {69 v := -170 for w, b := range used {71 if !b && (v < 0 || minCost[w].cost < minCost[v].cost) {72 v = w73 }74 }75 if v < 0 {76 break77 }78 used[v] = true79 totCost += minCost[v].cost80 if v == n { 81 ansCity = append(ansCity, minCost[v].v+1)82 } else if minCost[v].v == n { 83 ansCity = append(ansCity, v+1)84 } else if minCost[v].v != v { 85 ansWire = append(ansWire, pair{minCost[v].v + 1, v + 1})86 }87 for w, d := range dis[v] {88 if d < minCost[w].cost {89 minCost[w] = pair2{d, v}90 }91 }92 }93 94 Fprintln(out, totCost)95 Fprintln(out, len(ansCity))96 Fprintln(out, ansCity...)97 Fprintln(out, len(ansWire))98 for _, conn := range ansWire {99 Fprintln(out, conn.x, conn.y)100 }101}102 103104