- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 81 lines of Go from the credited upstream file 1495D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 CF1495D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 const mod = 99824435315 16 var n, m int17 Fscan(in, &n, &m)18 g := make([][]int, n)19 for ; m > 0; m-- {20 var v, w int21 Fscan(in, &v, &w)22 v--23 w--24 g[v] = append(g[v], w)25 g[w] = append(g[w], v)26 }27 28 dis := make([][]int, n)29 for i := range dis {30 d := make([]int, n)31 for j := range d {32 d[j] = -133 }34 d[i] = 035 q := []int{i}36 for len(q) > 0 {37 v := q[0]38 q = q[1:]39 for _, w := range g[v] {40 if d[w] < 0 {41 d[w] = d[v] + 142 q = append(q, w)43 }44 }45 }46 dis[i] = d47 }48 49 seen := make([]bool, n)50 for i, di := range dis {51 for j, dij := range di {52 clear(seen)53 ans := 154 for k, dik := range di {55 if k == i || k == j {56 continue57 }58 if dik+dis[j][k] == dij {59 if seen[dik] { 60 ans = 061 break62 }63 seen[dik] = true64 } else {65 c := 066 for _, w := range g[k] {67 if di[w]+1 == dik && dis[j][w]+1 == dis[j][k] {68 c++69 }70 }71 ans = ans * c % mod72 }73 }74 Fprint(out, ans, " ")75 }76 Fprintln(out)77 }78}79 8081