Approach
Breadth-first search
For Codeforces 1307D — Cow and Fields, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 74 lines of Go from the credited upstream file 1307D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 CF1307D(_r io.Reader, _w io.Writer) {12 in := bufio.NewScanner(_r)13 in.Split(bufio.ScanWords)14 read := func() (x int) {15 in.Scan()16 for _, b := range in.Bytes() {17 x = x*10 + int(b-'0')18 }19 return20 }21 max := func(a, b int) int {22 if a > b {23 return a24 }25 return b26 }27 28 n, m, k := read(), read(), read()29 sp := make([]int, k)30 for i := range sp {31 sp[i] = read() - 132 }33 g := make([][]int, n)34 for ; m > 0; m-- {35 v, w := read()-1, read()-136 g[v] = append(g[v], w)37 g[w] = append(g[w], v)38 }39 40 bfs := func(st int) []int {41 dep := make([]int, n)42 for i := range dep {43 dep[i] = -144 }45 dep[st] = 046 q := []int{st}47 for len(q) > 0 {48 var v int49 v, q = q[0], q[1:]50 for _, w := range g[v] {51 if dep[w] == -1 {52 dep[w] = dep[v] + 153 q = append(q, w)54 }55 }56 }57 return dep58 }59 depSt, depEnd := bfs(0), bfs(n-1)60 sort.Slice(sp, func(i, j int) bool { a, b := sp[i], sp[j]; return depSt[a]-depEnd[a] < depSt[b]-depEnd[b] })61 ans := 062 maxDepSt := int(-1e9)63 for _, v := range sp {64 ans = max(ans, maxDepSt+depEnd[v]+1)65 maxDepSt = max(maxDepSt, depSt[v])66 }67 if depSt[n-1] < ans {68 ans = depSt[n-1]69 }70 Fprint(_w, ans)71}72 7374