- 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
- 65 lines of Go from the credited upstream file 1493C.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 CF1493C(_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, k int16 var s []byte17 for Fscan(in, &T); T > 0; T-- {18 Fscan(in, &n, &k, &s)19 if n%k > 0 {20 Fprintln(out, -1)21 continue22 }23 cnt := make([]int, 26)24 for _, b := range s {25 cnt[b-'a']++26 }27 O:28 for _, c := range cnt {29 if c%k == 0 {30 continue31 }32 for i := n - 1; i >= 0; i-- {33 o:34 for s[i]++; s[i] <= 'z'; s[i]++ {35 cnt[s[i]-1-'a']--36 cnt[s[i]-'a']++37 left := n - 1 - i38 for _, c := range cnt {39 need := (k - c%k) % k40 if left < need {41 continue o42 }43 left -= need44 }45 for i++; left > 0; left-- { 46 s[i] = 'a'47 i++48 }49 for p := byte(0); i < n; i++ {50 for ; cnt[p]%k == 0; p++ {51 }52 s[i] = 'a' + p53 cnt[p]++54 }55 break O56 }57 cnt[25]--58 }59 }60 Fprintln(out, string(s))61 }62}63 6465