- 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
- 87 lines of Go from the credited upstream file 1530E.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 "bytes"6 . "fmt"7 "io"8 "sort"9 "strings"10)11 12/* 思考记录13- 全一样,直接输出14- 如果有只出现一次的字母,把只出现一次且最小的放到首位,其余排序放后面(这样可以构造答案为 0 的)15- 此时答案必然为 1,尝试拼凑字典序最小的:(假设 a 为最小,b 为次小,c 为第三小)16 - 如果最小字母的个数-2 不超过其余字母个数:aa+其余字母排序,其余 a 间隔插入排序中的字母17 - 如果只有两种字母:abb..bbaa..aa18 - 如果有三种或以上的字母:abaa..aac+其余字母排序19*/20 2122func CF1530E(_r io.Reader, _w io.Writer) {23 in := bufio.NewReader(_r)24 out := bufio.NewWriter(_w)25 defer out.Flush()26 27 var T int28 var s []byte29 for Fscan(in, &T); T > 0; T-- {30 Fscan(in, &s)31 n := len(s)32 cnt := [26]int{}33 for _, b := range s {34 cnt[b-'a']++35 }36 set := []int{}37 pc1 := -138 for i, c := range cnt {39 if c > 0 {40 set = append(set, i)41 if c == 1 && pc1 < 0 {42 pc1 = i43 }44 }45 }46 if len(set) == 1 {47 Fprintf(out, "%s\n", s)48 continue49 }50 if pc1 >= 0 {51 sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })52 b := 'a' + byte(pc1)53 i := bytes.IndexByte(s, b)54 Fprintf(out, "%c%s%s\n", b, s[:i], s[i+1:])55 continue56 }57 cnt0 := cnt[set[0]]58 b0 := 'a' + byte(set[0])59 if cnt0-2 <= n-cnt0 {60 Fprintf(out, "%c%c", b0, b0)61 cnt0 -= 262 for _, i := range set[1:] {63 for c := cnt[i]; c > 0; c-- {64 Fprintf(out, "%c", 'a'+byte(i))65 if cnt0 > 0 {66 Fprintf(out, "%c", b0)67 cnt0--68 }69 }70 }71 Fprintln(out)72 } else if len(set) == 2 {73 Fprintf(out, "%c%s%s\n", b0, strings.Repeat(string('a'+byte(set[1])), cnt[set[1]]), strings.Repeat(string('a'+byte(set[0])), cnt[set[0]]-1))74 } else {75 Fprintf(out, "%c%c%s%c", b0, 'a'+byte(set[1]), strings.Repeat(string('a'+byte(set[0])), cnt[set[0]]-1), 'a'+byte(set[2]))76 cnt[set[1]]--77 cnt[set[2]]--78 for _, i := range set[1:] {79 Fprintf(out, "%s", strings.Repeat(string('a'+byte(i)), cnt[i]))80 }81 Fprintln(out)82 }83 }84}85 8687