- 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
- 78 lines of Go from the credited upstream file 1540B.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 CF1540B(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const mod int64 = 1e9 + 713 const mod2 = (mod + 1) / 214 pow := func(x, n int64) (res int64) {15 res = 116 for ; n > 0; n >>= 1 {17 if n&1 > 0 {18 res = res * x % mod19 }20 x = x * x % mod21 }22 return23 }24 min := func(a, b int) int {25 if a < b {26 return a27 }28 return b29 }30 31 var n, v, w int32 Fscan(in, &n)33 dis := make([][]int, n)34 for i := range dis {35 dis[i] = make([]int, n)36 for j := range dis[i] {37 dis[i][j] = 1e938 }39 }40 for i := 1; i < n; i++ {41 Fscan(in, &v, &w)42 v--43 w--44 dis[v][w] = 145 dis[w][v] = 146 }47 for k := range dis {48 for i := range dis {49 for j := range dis {50 dis[i][j] = min(dis[i][j], dis[i][k]+dis[k][j])51 }52 }53 }54 55 f := make([][]int64, n+1)56 for i := range f {57 f[i] = make([]int64, n+1)58 f[0][i] = 159 }60 for i := 1; i <= n; i++ {61 for j := 1; j <= n; j++ {62 f[i][j] = (f[i-1][j] + f[i][j-1]) * mod2 % mod63 }64 }65 ans := int64(0)66 for _, d := range dis {67 for v, r := range dis {68 for w, dvw := range r[:v] {69 commonDis := (d[v] + d[w] - dvw) / 270 ans += f[d[v]-commonDis][d[w]-commonDis]71 }72 }73 }74 Fprint(out, ans%mod*pow(int64(n), mod-2)%mod)75}76 7778