- 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
- 86 lines of Go from the credited upstream file 1687C.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 . "fmt"5 "io"6)7 89func cf1687C(in io.Reader, out io.Writer) {10 var T, n, m int11 for Fscan(in, &T); T > 0; T-- {12 Fscan(in, &n, &m)13 s := make([]int, n+1)14 for i := 1; i <= n; i++ {15 Fscan(in, &s[i])16 }17 for i := 1; i <= n; i++ {18 var x int19 Fscan(in, &x)20 s[i] += s[i-1] - x21 }22 g := make([][]int, n+1)23 for range m {24 var l, r int25 Fscan(in, &l, &r)26 l--27 g[l] = append(g[l], r)28 g[r] = append(g[r], l)29 }30 if s[n] != 0 {31 Fprintln(out, "NO")32 continue33 }34 35 fa := make([]int, n+1)36 for i := range fa {37 fa[i] = i38 }39 find := func(x int) int {40 rt := x41 for fa[rt] != rt {42 rt = fa[rt]43 }44 for fa[x] != rt {45 fa[x], x = rt, fa[x]46 }47 return rt48 }49 50 q := []int{}51 for i, s := range s[:n] {52 if s == 0 {53 fa[i] = i + 154 q = append(q, i)55 }56 }57 for len(q) > 0 {58 n--59 l := q[0]60 q = q[1:]61 for _, r := range g[l] {62 if s[r] != 0 {63 continue64 }65 l := l66 if l > r {67 l, r = r, l68 }69 to := find(r)70 for j := find(l); j < r; j = find(j + 1) {71 s[j] = 072 fa[j] = to73 q = append(q, j)74 }75 }76 }77 if n == 0 {78 Fprintln(out, "YES")79 } else {80 Fprintln(out, "NO")81 }82 }83}84 8586