- 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
- 94 lines of Go from the credited upstream file 1366F.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 "cmp"5 . "fmt"6 "io"7 "slices"8)9 1011type vec66 struct{ x, y int }12 13func (a vec66) sub(b vec66) vec66 { return vec66{a.x - b.x, a.y - b.y} }14func (a vec66) dot(b vec66) int { return a.x*b.x + a.y*b.y }15func (a vec66) det(b vec66) int { return a.x*b.y - a.y*b.x }16 17func cf1366F(in io.Reader, out io.Writer) {18 const mod = 1_000_000_00719 var n, m, k, ans int20 Fscan(in, &n, &m, &k)21 type nb struct{ to, wt int }22 g := make([][]nb, n)23 for range m {24 var v, w, wt int25 Fscan(in, &v, &w, &wt)26 v--27 w--28 g[v] = append(g[v], nb{w, wt})29 g[w] = append(g[w], nb{v, wt})30 }31 32 f := make([]int, n)33 for i := 1; i < n; i++ {34 f[i] = -1e1835 }36 for range m {37 nf := make([]int, n)38 for i := range nf {39 nf[i] = -1e1840 }41 for v, fv := range f {42 if fv < 0 {43 continue44 }45 for _, e := range g[v] {46 nf[e.to] = max(nf[e.to], fv+e.wt)47 }48 }49 f = nf50 ans += slices.Max(f)51 }52 53 a := make([]vec66, 0, n)54 for i, fv := range f {55 if fv < 0 {56 continue57 }58 mx := 059 for _, e := range g[i] {60 mx = max(mx, e.wt)61 }62 a = append(a, vec66{mx, fv})63 }64 slices.SortFunc(a, func(a, b vec66) int { return cmp.Or(a.x-b.x, a.y-b.y) })65 q := a[:0]66 for _, v := range a {67 for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).det(v.sub(q[len(q)-1])) >= 0 {68 q = q[:len(q)-1]69 }70 q = append(q, v)71 }72 if len(q) > 1 && q[0].x == q[1].x {73 q = q[1:]74 }75 76 k -= m77 i := 178 for len(q) > 1 {79 nxt := (q[0].y-q[1].y)/(q[1].x-q[0].x) + 180 if nxt > k {81 break82 }83 if nxt > i {84 ans = (ans + (i+nxt-1)*(nxt-i)/2%mod*q[0].x + (nxt-i)*q[0].y) % mod85 i = nxt86 }87 q = q[1:]88 }89 ans = (ans + (i+k)*(k-i+1)/2%mod*q[0].x + (k-i+1)*q[0].y) % mod90 Fprint(out, ans)91}92 9394