Approach
Breadth-first search
For Codeforces 954D — Fight Against Traffic, 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
- 67 lines of Go from the credited upstream file 954D.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 CF954D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var n, m, v, w, start, end, ans int17 Fscan(in, &n, &m, &start, &end)18 start--19 end--20 g := make([][]int, n)21 for i := 0; i < m; i++ {22 Fscan(in, &v, &w)23 v--24 w--25 g[v] = append(g[v], w)26 g[w] = append(g[w], v)27 }28 29 bfs := func(st int) []int {30 depths := make([]int, n)31 vis := make([]bool, n)32 vis[st] = true33 queue := []int{st}34 for len(queue) > 0 {35 v, queue = queue[0], queue[1:]36 for _, w := range g[v] {37 if !vis[w] {38 vis[w] = true39 depths[w] = depths[v] + 140 queue = append(queue, w)41 }42 }43 }44 return depths45 }46 stDepths, edDepths := bfs(start), bfs(end)47 minDis := stDepths[end]48 for v, gi := range g {49 sort.Ints(gi)50 j := 051 for w := range g {52 if j == len(gi) || w < gi[j] {53 if w > v && stDepths[v]+edDepths[w]+1 >= minDis && stDepths[w]+edDepths[v]+1 >= minDis {54 ans++55 }56 } else {57 j++58 }59 }60 }61 Fprint(out, ans)62}63 64656667