Problem solution · Go

Codeforces 546E — Soldier and Traveling

Codeforces 546E — Soldier and Traveling: 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
124 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 546E — Soldier and Traveling, 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

  • 124 lines of Go from the credited upstream file 546E.go.
  • The implementation visibly relies on sequence storage.
  • 1 loop block detected, together with recursive traversal.

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 546E — Soldier and Traveling · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF546E(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush()	const inf int = 1e9	min := func(a, b int) int {		if a < b {			return a		}		return b	} 	var N, m, v, w, s, maxFlow int	Fscan(in, &N, &m)	st, end, n := 2*N, 2*N+1, 2*N+2	type nb struct{ to, rid, cap int }	g := make([][]nb, n)	addEdge := func(from, to, cap int) {		g[from] = append(g[from], nb{to, len(g[to]), cap})		g[to] = append(g[to], nb{from, len(g[from]) - 1, 0})	}	for i := 0; i < N; i++ {		Fscan(in, &v)		addEdge(st, i, v)		s += v	}	sum := s	for i := N; i < 2*N; i++ {		Fscan(in, &v)		addEdge(i, end, v)		s -= v	}	if s != 0 {		Fprint(out, "NO")		return	}	for i := 0; i < N; i++ {		addEdge(i, i+N, inf)	}	for ; m > 0; m-- {		Fscan(in, &v, &w)		v--		w--		addEdge(v, w+N, inf)		addEdge(w, v+N, inf)	} 	dep := make([]int, n)	bfs := func() bool {		for i := range dep {			dep[i] = -1		}		dep[st] = 0		q := []int{st}		for len(q) > 0 {			v := q[0]			q = q[1:]			for _, e := range g[v] {				if w := e.to; e.cap > 0 && dep[w] < 0 {					dep[w] = dep[v] + 1					q = append(q, w)				}			}		}		return dep[end] >= 0	}	var it []int	var dfs func(int, int) int	dfs = func(v, minF int) int {		if v == end {			return minF		}		for ; it[v] < len(g[v]); it[v]++ {			e := &g[v][it[v]]			if w := e.to; e.cap > 0 && dep[w] > dep[v] {				if f := dfs(w, min(minF, e.cap)); f > 0 {					e.cap -= f					g[w][e.rid].cap += f					return f				}			}		}		return 0	}	for bfs() {		it = make([]int, n)		for {			if f := dfs(st, inf); f > 0 {				maxFlow += f			} else {				break			}		}	}	if maxFlow < sum {		Fprint(out, "NO")		return	}	Fprintln(out, "YES")	for _, es := range g[:N] {		ans := make([]int, N)		for _, e := range es {			if w := e.to; N <= w && w < 2*N {				ans[w-N] = g[w][e.rid].cap			}		}		for _, v := range ans {			Fprint(out, v, " ")		}		Fprintln(out)	}} //func main() { CF546E(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 ↗