Bibi's DevLog ๐Ÿค“๐ŸŽ

[๋ฐฑ์ค€ 3004] ์ฒด์ŠคํŒ ์กฐ๊ฐ ๋ณธ๋ฌธ

ํ”„๋กœ๊ทธ๋ž˜๋ฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด Swift

[๋ฐฑ์ค€ 3004] ์ฒด์ŠคํŒ ์กฐ๊ฐ

๋น„๋น„ bibi 2022. 9. 30. 12:08

3004๋ฒˆ: ์ฒด์ŠคํŒ ์กฐ๊ฐ

  • ๋‚˜๋ฌดํŒ์„ n๋ฒˆ ์ž๋ฅผ ๋•Œ ์ตœ๋Œ€ ๋ช‡ ์กฐ๊ฐ ์ด ๋˜๋Š”์ง€ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ
  • ํฌ๊ฒŒ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•๊ณผ ๊ทœ์น™์„ ์ฐพ์•„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.
  • ์‹œ๊ฐ„์ œํ•œ์— ๊ฑธ๋ฆด๊นŒ ๋ด ๊ทœ์น™์„ ์ฐพ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผํ–ˆ๋‹ค.
    • ๊ทผ๋ฐ ๊ฒฐ๊ตญ ์‚ฌ์šฉํ•œ ๊ฒŒ reduce๋ผ์„œ.. ์‰ฝ๊ฒŒ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ ‘๊ทผํ• ๊ฑธ ์‹ถ๊ธฐ๋„. (์‹œ๊ฐ„์ œํ•œ์— ๊ฑธ๋ฆฌ์ง„ ์•Š๋Š” ๋“ฏ - n์˜ ์ตœ๋Œ“๊ฐ’์ด 100์ด๋ผ)
  • ๊ทœ์น™
    • 1 : 2
    • 2 : 4
    • 3 : 6
    • 4 : 9
    • 5 : 12
    • 6 : 16
    • 7 : 20
    • 8 : 25
    • 9 : 30
    • 10 : 36

ํ’€์ด1 (๋‚˜์˜ ํ’€์ด)

  • 1์ผ๋•Œ ์ดˆ๊ธฐ๊ฐ’์ด 2, ๋‚˜๋จธ์ง€๋Š” +2 +2 +3 +3 +4 +4 .. ํŒจํ„ด
  • n์ด ํ™€์ˆ˜์ผ ๋•Œ๋Š” ์ดˆ๊ธฐ๊ฐ’ 2์—, 2๋ถ€ํ„ฐ (n + 1) / 2 ๊นŒ์ง€ ๋”ํ•œ ๊ฐ’์˜ ๊ณฑํ•˜๊ธฐ 2
    • n=7 โ†’ 2 + (2โ€ฆ4) * 2 = 20
  • n์ด ์ง์ˆ˜์ผ ๋•Œ๋Š” ์ดˆ๊ธฐ๊ฐ’ 2์—, 2๋ถ€ํ„ฐ n / 2 ๊นŒ์ง€ ๋”ํ•œ ๊ฐ’์˜ ๊ณฑํ•˜๊ธฐ 2, ๊ทธ๋ฆฌ๊ณ  (n / 2) + 1 ์„ ๋”ํ•จ
    • n=8 โ†’ 2 + (2โ€ฆ4) * 2 + 5 = 25
  • ๋‹ค๋งŒ ์ด ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ..
    • ๋ฒ”์œ„ ์—ฐ์‚ฐ์ž ๋–„๋ฌธ์— n์ด 1์ผ ๋•Œ์™€ 2์ผ ๋•Œ๋Š” ์ง์ ‘ ์ฒ˜๋ฆฌ ํ•„์š”
    • ๋ฐ˜๋ณต๋ฌธ์„ ํ”ผํ•˜๋ ค๊ณ  ๊ณต์‹์„ ๊ตฌํ•ด๋ณด๋ ค ํ–ˆ์ง€๋งŒ ๊ฒฐ๊ตญ reduce๋ฅผ ์‚ฌ์šฉํ–ˆ์Œใ…Žใ…Ž
let cut = Int(readLine()!)!
var answer = 0
if cut == 1 {
    answer = 2
} else if cut == 2 {
    answer = 4
} else {
    if cut % 2 == 1 {
        let cutHalf = (cut + 1) / 2
        answer = 2 + (2...cutHalf).reduce(0, +) * 2
    } else {
        let cutHalf = cut / 2
        answer = 2 + (2...cutHalf).reduce(0, +) * 2 + (cut / 2 + 1)
    }
}
print(answer)

ํ’€์ด 2 ( ์ •๋‹ต์ฝ”๋“œ ์ค‘ ๋ฐœ์ทŒ )

์•„๋ž˜์™€ ๊ฐ™์ด ์ •๋ง ๊ณต์‹์„ ์ฐพ์•„ ๊ณ„์‚ฐํ•˜์‹  ๋ถ„๋“ค๋„ ์žˆ์—ˆ๋‹ค. ๐Ÿ‘

๋ฐ˜๋ณต๋ฌธ์„ ์“ฐ์ง€ ์•Š์œผ๋ฏ€๋กœ ์‹œ๊ฐ„๋ณต์žก๋„๋ฉด์—์„œ ์œ ๋ฆฌํ•˜๋‹ค.

var x = Int(readLine()!)!
print(((x/2)+1)*(x-(x/2)+1))
let input = Int(readLine()!)!
if input % 2 == 0 {
    let a = input / 2 + 1
    print(a * a)
} else {
    let a = (input + 1) / 2 + 1
    print(a * a - a)
}