Approach
Depth-first search
For Codeforces 241E — Flights, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 87 lines of Go from the credited upstream file 241E.go.
- The implementation visibly relies on sequence storage.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 cf241E(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var n, m int14 Fscan(in, &n, &m)15 x := make([]int, m)16 y := make([]int, m)17 G := make([][]int, n+1)18 RG := make([][]int, n+1)19 for i := range m {20 Fscan(in, &x[i], &y[i])21 G[x[i]] = append(G[x[i]], y[i])22 RG[y[i]] = append(RG[y[i]], x[i])23 }24 25 vis := make([][2]bool, n+1)26 var dfs func(int, int)27 dfs = func(v, tp int) {28 vis[v][tp] = true29 var g []int30 if tp == 0 {31 g = G[v]32 } else {33 g = RG[v]34 }35 for _, w := range g {36 if !vis[w][tp] {37 dfs(w, tp)38 }39 }40 }41 dfs(1, 0)42 dfs(n, 1)43 44 dis := make([]int, n+1)45 for i := 2; i <= n; i++ {46 dis[i] = 1e947 }48 49 loop := 050 for {51 loop++52 if loop > n {53 Fprint(out, "No")54 return55 }56 changed := false57 for i := range m {58 X, Y := x[i], y[i]59 if vis[X][0] && vis[Y][1] {60 if dis[Y] > dis[X]+2 {61 dis[Y] = dis[X] + 262 changed = true63 }64 if dis[X] > dis[Y]-1 {65 dis[X] = dis[Y] - 166 changed = true67 }68 }69 }70 if !changed {71 break72 }73 }74 75 Fprintln(out, "Yes")76 for i := range m {77 X, Y := x[i], y[i]78 if vis[X][0] && vis[Y][1] {79 Fprintln(out, dis[Y]-dis[X])80 } else {81 Fprintln(out, 1)82 }83 }84}85 8687