- 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 1158C.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)8 910func CF1158C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n int16o:17 for Fscan(in, &T); T > 0; T-- {18 Fscan(in, &n)19 pp := make([][]int, n+2)20 pos := make([]int, n)21 for i := range pos {22 Fscan(in, &pos[i])23 if pos[i] == -1 {24 pos[i] = i + 225 }26 pp[pos[i]] = append(pp[pos[i]], i)27 }28 ans := make([]int, n)29 v := 130 for _, ps := range pp {31 for i := len(ps) - 1; i >= 0; i-- {32 ans[ps[i]] = v33 v++34 }35 }36 type pair struct{ v, i int }37 s := []pair{{1e9, n}}38 for i := n - 1; i >= 0; i-- {39 v := ans[i]40 for {41 if top := s[len(s)-1]; top.v > v {42 if top.i+1 != pos[i] {43 Fprintln(out, -1)44 continue o45 }46 break47 }48 s = s[:len(s)-1]49 }50 s = append(s, pair{v, i})51 }52 for _, v := range ans {53 Fprint(out, v, " ")54 }55 Fprintln(out)56 }57}58 5960