Problem solution · Go

Codeforces 1320B — Navigation System

Codeforces 1320B — Navigation System: a Go solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Breadth-first search
Source
EndlessCheng Codeforces Go
Length
64 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Codeforces 1320B — Navigation System, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 64 lines of Go from the credited upstream file 1320B.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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 1320B — Navigation System · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF1320B(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	var n, m, v, w, k, min, extra int	Fscan(in, &n, &m)	g := make([][]int, n)	rg := make([][]int, n)	for ; m > 0; m-- {		Fscan(in, &v, &w)		v--		w--		g[v] = append(g[v], w)		rg[w] = append(rg[w], v)	}	Fscan(in, &k)	path := make([]int, k)	for i := range path {		Fscan(in, &path[i])		path[i]--	} 	// 在反图 rg 上跑 BFS,得到每个点到终点的最短距离 dis	// 这样就能知道有没有跟着导航走了	dis := make([]int, n)	vis := make([]bool, n)	vis[path[k-1]] = true	q := []int{path[k-1]}	for len(q) > 0 {		v, q = q[0], q[1:]		for _, w := range rg[v] {			if !vis[w] {				vis[w] = true				dis[w] = dis[v] + 1				q = append(q, w)			}		}	} 	for i, cur := range path[:k-1] {		next := path[i+1]		if dis[next] >= dis[cur] { // 偏航了,下一站距终点的距离没有变得更小(没有跟着导航走)			min++ // 导航一定会更新推荐线路			continue		}		for _, other := range g[cur] {			if other != next && dis[other] == dis[next] { // 存在另一条最短路径				extra++				break			}		}	}	Fprint(out, min, min+extra)} //func main() { CF1320B(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗