Approach
Breadth-first search
For Codeforces 1082G — Petya and Graph, 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
- 91 lines of Go from the credited upstream file 1082G.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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7)8 910func cf1082G(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const inf int = 1e1813 var n, m, cost, v, w, profit, tot int14 Fscan(in, &n, &m)15 16 st := 017 end := n + m + 118 type nb struct{ to, rid, cap int }19 g := make([][]nb, end+1)20 addEdge := func(from, to, cap int) {21 g[from] = append(g[from], nb{to, len(g[to]), cap})22 g[to] = append(g[to], nb{from, len(g[from]) - 1, 0})23 }24 for i := 1; i <= n; i++ {25 Fscan(in, &cost)26 addEdge(m+i, end, cost)27 }28 for i := 1; i <= m; i++ {29 Fscan(in, &v, &w, &profit)30 addEdge(st, i, profit)31 addEdge(i, m+v, inf)32 addEdge(i, m+w, inf)33 tot += profit34 }35 36 var d []int37 bfs := func() bool {38 d = make([]int, len(g))39 d[st] = 140 q := []int{st}41 for len(q) > 0 {42 v := q[0]43 q = q[1:]44 for _, e := range g[v] {45 if w := e.to; e.cap > 0 && d[w] == 0 {46 d[w] = d[v] + 147 q = append(q, w)48 }49 }50 }51 return d[end] > 052 }53 var iter []int54 var dfs func(int, int) int55 dfs = func(v, minF int) int {56 if v == end {57 return minF58 }59 for ; iter[v] < len(g[v]); iter[v]++ {60 e := &g[v][iter[v]]61 w := e.to62 if e.cap > 0 && d[w] > d[v] {63 f := dfs(w, min(minF, e.cap))64 if f > 0 {65 e.cap -= f66 g[w][e.rid].cap += f67 return f68 }69 }70 }71 return 072 }73 dinic := func() (maxFlow int) {74 for bfs() {75 iter = make([]int, len(g))76 for {77 f := dfs(st, inf)78 if f > 0 {79 maxFlow += f80 } else {81 break82 }83 }84 }85 return86 }87 Fprint(out, tot-dinic())88}89 9091