From 62194f5fbc5a5352304d8eb6a0d4e44a346b546c Mon Sep 17 00:00:00 2001 From: tiennm99 Date: Sun, 7 Dec 2025 11:02:09 +0700 Subject: [PATCH] Update exam.go --- go/exam/exam.go | 47 +++++++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/go/exam/exam.go b/go/exam/exam.go index 4023d02..5cea475 100644 --- a/go/exam/exam.go +++ b/go/exam/exam.go @@ -23,18 +23,17 @@ func calc(a int64, op byte, b int64) int64 { return a * b } +func ts(x int64) string { + return strconv.FormatInt(x, 10) +} + func getAll(nums []int64, ops []byte) []Pair { sz := len(nums) - var result []Pair - seen := make(map[int64]bool) - - ts := func(x int64) string { - return strconv.FormatInt(x, 10) - } + var all []Pair if sz == 2 { v := calc(nums[0], ops[0], nums[1]) - result = append(result, Pair{v, ts(nums[0]) + string(ops[0]) + ts(nums[1])}) + all = append(all, Pair{v, ts(nums[0]) + string(ops[0]) + ts(nums[1])}) } else if sz == 3 { a, b, c := nums[0], nums[1], nums[2] o1, o2 := ops[0], ops[1] @@ -42,29 +41,32 @@ func getAll(nums []int64, ops []byte) []Pair { v2 := calc(calc(a, o1, b), o2, c) s1 := ts(a) + string(o1) + "(" + ts(b) + string(o2) + ts(c) + ")" s2 := "(" + ts(a) + string(o1) + ts(b) + ")" + string(o2) + ts(c) - result = append(result, Pair{v1, s1}) - seen[v1] = true - if !seen[v2] { - seen[v2] = true - result = append(result, Pair{v2, s2}) - } + all = append(all, Pair{v1, s1}, Pair{v2, s2}) } else { a, b, c, d := nums[0], nums[1], nums[2], nums[3] o1, o2, o3 := ops[0], ops[1], ops[2] - all := []Pair{ + all = []Pair{ {calc(a, o1, calc(b, o2, calc(c, o3, d))), ts(a) + string(o1) + "(" + ts(b) + string(o2) + "(" + ts(c) + string(o3) + ts(d) + "))"}, {calc(a, o1, calc(calc(b, o2, c), o3, d)), ts(a) + string(o1) + "((" + ts(b) + string(o2) + ts(c) + ")" + string(o3) + ts(d) + ")"}, {calc(calc(a, o1, b), o2, calc(c, o3, d)), "(" + ts(a) + string(o1) + ts(b) + ")" + string(o2) + "(" + ts(c) + string(o3) + ts(d) + ")"}, {calc(calc(a, o1, calc(b, o2, c)), o3, d), "(" + ts(a) + string(o1) + "(" + ts(b) + string(o2) + ts(c) + "))" + string(o3) + ts(d)}, {calc(calc(calc(a, o1, b), o2, c), o3, d), "((" + ts(a) + string(o1) + ts(b) + ")" + string(o2) + ts(c) + ")" + string(o3) + ts(d)}, } - for _, p := range all { - if !seen[p.val] { - seen[p.val] = true - result = append(result, p) - } + } + + sort.SliceStable(all, func(i, j int) bool { + return all[i].val < all[j].val + }) + + var result []Pair + seen := make(map[int64]bool) + for _, p := range all { + if !seen[p.val] { + seen[p.val] = true + result = append(result, p) } } + return result } @@ -102,8 +104,13 @@ func exam(in *os.File, out *os.File) { for i := 0; i < n; i++ { order[i] = i } + sort.Slice(order, func(i, j int) bool { - return len(exprs[order[i]]) < len(exprs[order[j]]) + li, lj := len(exprs[order[i]]), len(exprs[order[j]]) + if li != lj { + return li < lj + } + return order[i] < order[j] }) result := make([]string, n)