- 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
- 60 lines of Go from the credited upstream file 1857G.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 "sort"8)9 1011func CF1857G(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 const mod = 99824435316 pow := func(x, n int64) (res int64) {17 res = 118 for ; n > 0; n /= 2 {19 if n%2 > 0 {20 res = res * x % mod21 }22 x = x * x % mod23 }24 return25 }26 27 var T, n, s int28 for Fscan(in, &T); T > 0; T-- {29 Fscan(in, &n, &s)30 es := make([]struct{ v, w, wt int }, n-1)31 for i := range es {32 Fscan(in, &es[i].v, &es[i].w, &es[i].wt)33 }34 sort.Slice(es, func(i, j int) bool { return es[i].wt < es[j].wt })35 fa := make([]int, n+1)36 sz := make([]int, n+1)37 for i := range fa {38 fa[i] = i39 sz[i] = 140 }41 var find func(int) int42 find = func(x int) int {43 if fa[x] != x {44 fa[x] = find(fa[x])45 }46 return fa[x]47 }48 ans := int64(1)49 for _, e := range es {50 v, w := find(e.v), find(e.w)51 fa[v] = w52 ans = ans * pow(int64(s-e.wt+1), int64(sz[v])*int64(sz[w])-1) % mod53 sz[w] += sz[v]54 }55 Fprintln(out, ans)56 }57}58 5960