Approach
Breadth-first search
For Codeforces 628F — Bear and Fair Set, 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
- 103 lines of Go from the credited upstream file 628F.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks 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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6 "math"7 "slices"8)9 1011func cf628F(in io.Reader, out io.Writer) {12 var n, maxV, q int13 Fscan(in, &n, &maxV, &q)14 q += 215 type pair struct{ r, num int }16 a := make([]pair, q)17 for i := 1; i < q-1; i++ {18 Fscan(in, &a[i].r, &a[i].num)19 }20 a[q-1] = pair{maxV, n}21 slices.SortFunc(a, func(a, b pair) int { return a.r - b.r })22 23 const k = 524 st := q + k25 end := st + 126 type nb struct{ to, rid, cap int }27 g := make([][]nb, end+1)28 addEdge := func(from, to, cap int) {29 g[from] = append(g[from], nb{to, len(g[to]), cap})30 g[to] = append(g[to], nb{from, len(g[from]) - 1, 0})31 }32 33 for i := 1; i < q; i++ {34 num := a[i].num - a[i-1].num35 l, r := a[i-1].r, a[i].r36 if num < 0 || num > r-l {37 Fprint(out, "unfair")38 return39 }40 addEdge(st, i, num)41 for j := range k {42 addEdge(i, j+q, (r+k-j)/k-(l+k-j)/k)43 }44 }45 for j := range k {46 addEdge(j+q, end, n/k)47 }48 49 dis := make([]int, len(g))50 bfs := func() bool {51 clear(dis)52 dis[st] = 153 q := []int{st}54 for len(q) > 0 {55 v := q[0]56 q = q[1:]57 for _, e := range g[v] {58 if w := e.to; e.cap > 0 && dis[w] == 0 {59 dis[w] = dis[v] + 160 q = append(q, w)61 }62 }63 }64 return dis[end] > 065 }66 iter := make([]int, len(g))67 var dfs func(int, int) int68 dfs = func(v, totalFlow int) (curFlow int) {69 if v == end {70 return totalFlow71 }72 for ; iter[v] < len(g[v]); iter[v]++ {73 e := &g[v][iter[v]]74 if w := e.to; e.cap > 0 && dis[w] > dis[v] {75 f := dfs(w, min(totalFlow-curFlow, e.cap))76 if f == 0 {77 continue78 }79 e.cap -= f80 g[w][e.rid].cap += f81 curFlow += f82 if curFlow == totalFlow {83 break84 }85 }86 }87 return88 }89 maxFlow := 090 for bfs() {91 clear(iter)92 maxFlow += dfs(st, math.MaxInt)93 }94 95 if maxFlow == n {96 Fprint(out, "fair")97 } else {98 Fprint(out, "unfair")99 }100}101 102103