- 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
- 69 lines of Go from the credited upstream file 1713E.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 cf1713E(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n int14 for Fscan(in, &T); T > 0; T-- {15 Fscan(in, &n)16 fa := make([]int, n)17 for i := range fa {18 fa[i] = i19 }20 dis := make([]int, n)21 var find func(int) int22 find = func(x int) int {23 if fa[x] != x {24 ffx := find(fa[x])25 dis[x] ^= dis[fa[x]]26 fa[x] = ffx27 }28 return fa[x]29 }30 merge := func(from, to int, b bool) bool {31 d := 032 if b {33 d = 134 }35 ff, ft := find(from), find(to)36 if ff != ft {37 dis[ff] = dis[to] ^ dis[from] ^ d38 fa[ff] = ft39 return true40 }41 return dis[from]^dis[to] == d42 }43 44 a := make([][]int, n)45 for i := range a {46 a[i] = make([]int, n)47 for j := range a[i] {48 Fscan(in, &a[i][j])49 }50 }51 for i, r := range a {52 for j := i + 1; j < n; j++ {53 v, w := r[j], a[j][i]54 if v != w && merge(i, j, v > w) != (v < w) {55 r[j], a[j][i] = w, v56 }57 }58 }59 for _, r := range a {60 for _, v := range r {61 Fprint(out, v, " ")62 }63 Fprintln(out)64 }65 }66}67 6869