ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

1431๋ฒˆ: ์‹œ๋ฆฌ์–ผ ๋ฒˆํ˜ธ

์ฒซ์งธ ์ค„์— ๊ธฐํƒ€์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. N์€ 1,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ์‹œ๋ฆฌ์–ผ ๋ฒˆํ˜ธ๊ฐ€ ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์‹œ๋ฆฌ์–ผ ๋ฒˆํ˜ธ์˜ ๊ธธ์ด๋Š” ์ตœ๋Œ€ 50์ด๊ณ , ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž ๋˜๋Š” ์ˆซ์ž๋กœ๋งŒ ์ด๋ฃจ

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/1431
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	fmt.Fscanln(reader, &n)

	var serials = make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanln(reader, &serials[i])
	}

	sort.Slice(serials, func(i, j int) bool {
		if len(serials[i]) < len(serials[j]) {
			return true
		} else if len(serials[i]) == len(serials[j]) {
			var sumI, sumJ int
			for k := 0; k < len(serials[i]); k++ {
				if val, err := strconv.Atoi(string(serials[i][k])); err == nil {
					sumI += val
				}
				if val, err := strconv.Atoi(string(serials[j][k])); err == nil {
					sumJ += val
				}
			}
			if sumI < sumJ {
				return true
			} else if sumI == sumJ {
				return serials[i] < serials[j]
			}
			return false
		}
		return false
	})
	for i := 0; i < n; i++ {
		fmt.Fprintln(writer, serials[i])
	}
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/1431
import sys

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    serials = []
    for i in range(n):
        serials.append(sys.stdin.readline().rstrip())
    serials = sorted(serials, key=lambda s: (len(s), sum([int(i) for i in s if type(i)== int or i.isdigit()]), s))
    for i in serials:
        print(i)
728x90
๋Œ“๊ธ€