Approach
Sorting and greedy selection
For Codeforces 1358F — Tasty Cookie, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 117 lines of Go from the credited upstream file 1358F.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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)10 1112func CF1358F(_r io.Reader, out io.Writer) {13 eq := func(a, b []int64) bool {14 for i, v := range a {15 if v != b[i] {16 return false17 }18 }19 return true20 }21 eqR := func(a, b []int64) bool {22 for i, v := range a {23 if v != b[len(a)-1-i] {24 return false25 }26 }27 return true28 }29 30 in := bufio.NewReader(_r)31 var n int32 Fscan(in, &n)33 a := make([]int64, n)34 for i := range a {35 Fscan(in, &a[i])36 }37 b := make([]int64, n)38 for i := range b {39 Fscan(in, &b[i])40 }41 if n == 1 {42 if a[0] != b[0] {43 Fprint(out, "IMPOSSIBLE")44 } else {45 Fprint(out, "SMALL\n0")46 }47 return48 }49 50 cntP := int64(0)51 ans := []byte{}52 x, y := a[0], a[1]53 if x > y {54 x, y = y, x55 }56 for !eq(b, a) {57 if b[0] < 1 {58 Fprint(out, "IMPOSSIBLE")59 return60 }61 if eqR(b, a) {62 ans = append(ans, 'R')63 break64 }65 if sort.SliceIsSorted(b, func(i, j int) bool { return b[i] >= b[j] }) {66 for i, j := 0, n-1; i < j; i++ {67 b[i], b[j] = b[j], b[i]68 j--69 }70 ans = append(ans, 'R')71 } else if sort.SliceIsSorted(b, func(i, j int) bool { return b[i] <= b[j] }) {72 if n == 2 {73 c := b[1] / b[0]74 if b[0] == x {75 if (b[1]-y)%x != 0 {76 Fprint(out, "IMPOSSIBLE")77 return78 }79 c = (b[1] - y) / x80 b[1] = y81 } else {82 b[1] %= b[0]83 }84 cntP += c85 if cntP <= 2e5 {86 ans = append(ans, bytes.Repeat([]byte{'P'}, int(c))...)87 }88 continue89 }90 for i := n - 1; i > 0; i-- {91 b[i] -= b[i-1]92 }93 cntP++94 if cntP <= 2e5 {95 ans = append(ans, 'P')96 }97 } else {98 Fprint(out, "IMPOSSIBLE")99 return100 }101 }102 if cntP > 2e5 {103 Fprintln(out, "BIG")104 Fprint(out, cntP)105 return106 }107 for i, j := 0, len(ans)-1; i < j; i++ {108 ans[i], ans[j] = ans[j], ans[i]109 j--110 }111 Fprintln(out, "SMALL")112 Fprintln(out, len(ans))113 Fprint(out, string(ans))114}115 116117