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

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

 

17626๋ฒˆ: Four Squares

๋ผ๊ทธ๋ž‘์ฃผ๋Š” 1770๋…„์— ๋ชจ๋“  ์ž์—ฐ์ˆ˜๋Š” ๋„ท ํ˜น์€ ๊ทธ ์ดํ•˜์˜ ์ œ๊ณฑ์ˆ˜์˜ ํ•ฉ์œผ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ฆ๋ช…ํ•˜์˜€๋‹ค. ์–ด๋–ค ์ž์—ฐ์ˆ˜๋Š” ๋ณต์ˆ˜์˜ ๋ฐฉ๋ฒ•์œผ๋กœ ํ‘œํ˜„๋œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, 26์€ 52๊ณผ 12์˜ ํ•ฉ์ด๋‹ค; ๋˜ํ•œ 42 + 32 + 1

www.acmicpc.net


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

๐ŸŽจ Go

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

import (
	"bufio"
	"fmt"
	"os"
)

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

	var n int
	fmt.Fscanln(reader, &n)
	fmt.Fprintln(writer, getSquareCount(n))
}

func getSquareCount(n int) int {
	dp := make([]int, n+1)
	dp[1] = 1

	for i := 2; i < n+1; i++ {
		minCount := n
		for j := 1; j*j <= i; j++ { // i๋ณด๋‹ค ์ž‘์€ ์ œ๊ณฑ์ˆ˜๋“ค์˜ dp๊ฐ’ ์ค‘ ์ตœ์†Œ๊ฐ’์„ ๊ตฌํ•œ๋‹ค
			if minCount > dp[i-j*j] {
				minCount = dp[i-j*j]
			}
		}
		dp[i] = minCount + 1 // ์ตœ์†Œ๊ฐ’๊ณผ ํ•ด๋‹น ์ œ๊ณฑ์ˆ˜๋ฅผ ๋”ํ•˜๋Š” ๊ฒฝ์šฐ๋กœ 1์„ ๋”ํ•œ ๊ฐ’์„ dp[i]์— ์ €์žฅํ•œ๋‹ค
	}
	return dp[n]
}

๐ŸŽจ Python3

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

def get_square_count(n):
    min_count = 4
    for i in range(int(n**0.5), 0, -1):
        if i*i == n:
            min_count = min(min_count, 1)
            break
        else:
            new_n = n - i*i
            for j in range(int(new_n**0.5), 0, -1):
                if new_n == j*j:
                    min_count = min(min_count, 2)
                    break
                else:
                    new_n2 = n - i*i - j*j
                    for k in range(int(new_n2**0.5), 0, -1):
                        if new_n2 == k*k:
                            min_count = min(min_count, 3)
    return min_count

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    print(get_square_count(n))

# ์‹œ๊ฐ„ ์ดˆ๊ณผ ๋ฐœ์ƒ
# def get_square_count(n): 
#     dp = [0 for i in range(n+1)]
#     dp[1] = 1
    
#     for i in range(2, n+1):
#         min_count = n
#         j = 1
#         while j*j <= i:
#             if min_count > dp[i-j*j]:
#                 min_count = dp[i-j*j]
#             j += 1 
#         dp[i] = min_count + 1
    
#     return dp[n]
728x90
๋Œ“๊ธ€