- 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
- 125 lines of Go from the credited upstream file 1900E.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 "math"8 "slices"9)10 11func CF1900E(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var T, n, m int17 for Fscan(in, &T); T > 0; T-- {18 Fscan(in, &n, &m)19 a := make([]int, n)20 for i := range a {21 Fscan(in, &a[i])22 }23 g := make([][]int, n)24 for ; m > 0; m-- {25 var v, w int26 Fscan(in, &v, &w)27 g[v-1] = append(g[v-1], w-1)28 }29 30 allScc := [][]int{}31 dfn := make([]int, n)32 ts := 033 st := []int{}34 var tarjan func(int) int35 tarjan = func(v int) int {36 ts++37 dfn[v] = ts38 lowV := ts39 st = append(st, v)40 for _, w := range g[v] {41 if dfn[w] == 0 {42 lowV = min(lowV, tarjan(w))43 } else {44 lowV = min(lowV, dfn[w])45 }46 }47 if dfn[v] == lowV {48 scc := []int{}49 for {50 w := st[len(st)-1]51 st = st[:len(st)-1]52 dfn[w] = math.MaxInt53 scc = append(scc, w)54 if w == v {55 break56 }57 }58 allScc = append(allScc, scc)59 }60 return lowV61 }62 for i, t := range dfn {63 if t == 0 {64 tarjan(i)65 }66 }67 slices.Reverse(allScc)68 69 ns := len(allScc)70 a2 := make([]int, ns)71 sid := make([]int, n)72 for i, cc := range allScc {73 for _, v := range cc {74 a2[i] += a[v]75 sid[v] = i76 }77 }78 79 g2 := make([][]int, ns)80 deg := make([]int, ns)81 for v, ws := range g {82 v = sid[v]83 for _, w := range ws {84 w = sid[w]85 if v != w {86 g2[v] = append(g2[v], w)87 deg[w]++88 }89 }90 }91 92 type pair struct{ len, s int }93 f := make([]pair, ns)94 q := make([]int, 0, ns)95 for i, d := range deg {96 if d == 0 {97 q = append(q, i)98 }99 }100 ans := pair{}101 gr := func(p, q pair) bool { return p.len > q.len || p.len == q.len && p.s < q.s }102 for len(q) > 0 {103 v := q[0]104 q = q[1:]105 p := f[v]106 p.len += len(allScc[v])107 p.s += a2[v]108 if gr(p, ans) {109 ans = p110 }111 for _, w := range g2[v] {112 if gr(p, f[w]) {113 f[w] = p114 }115 if deg[w]--; deg[w] == 0 {116 q = append(q, w)117 }118 }119 }120 Fprintln(out, ans.len, ans.s)121 }122}123 124125