๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/๋ฐฑ์ค€

[๋ฐฑ์ค€] #2470 ๋‘ ์šฉ์•ก (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

  • ์ž…๋ ฅ
    • ์ฒซ์งธ ์ค„์—๋Š” ์ „์ฒด ์šฉ์•ก์˜ ์ˆ˜ N์ด ์ž…๋ ฅ๋œ๋‹ค. N์€ 2 ์ด์ƒ 100,000 ์ดํ•˜์ด๋‹ค.
    • ๋‘˜์งธ ์ค„์—๋Š” ์šฉ์•ก์˜ ํŠน์„ฑ๊ฐ’์„ ๋‚˜ํƒ€๋‚ด๋Š” N๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ๋นˆ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. ์ด ์ˆ˜๋“ค์€ ๋ชจ๋‘ -1,000,000,000 ์ด์ƒ 1,000,000,000 ์ดํ•˜์ด๋‹ค.
  • ์ถœ๋ ฅ
    • ์ฒซ์งธ ์ค„์— ํŠน์„ฑ๊ฐ’์ด 0์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์šฉ์•ก์„ ๋งŒ๋“ค์–ด๋‚ด๋Š” ๋‘ ์šฉ์•ก์˜ ํŠน์„ฑ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ถœ๋ ฅํ•ด์•ผ ํ•˜๋Š” ๋‘ ์šฉ์•ก์€ ํŠน์„ฑ๊ฐ’์˜ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•œ๋‹ค. ํŠน์„ฑ๊ฐ’์ด 0์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์šฉ์•ก์„ ๋งŒ๋“ค์–ด๋‚ด๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋‘ ๊ฐœ ์ด์ƒ์ผ ๊ฒฝ์šฐ์—๋Š” ๊ทธ ์ค‘ ์•„๋ฌด๊ฒƒ์ด๋‚˜ ํ•˜๋‚˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

2. ์ฝ”๋“œ

solution1.py

import sys
input = sys.stdin.readline

n = int(input())
ary = list(map(int, input().split()))
ary.sort()
left = 0 #๋งจ ์•ž
right = n-1 #๋งจ ๋

min_hab = 2000000001
answer = []

while left < right:
    L = ary[left]
    R = ary[right]

    hab = L + R
    # ๋‘ ์šฉ์•ก์˜ ํ•ฉ์ด 0๊ณผ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์šฉ์•ก์„ ์ •๋‹ต์— ๋‹ด์•„์ฃผ๊ธฐ
    if abs(hab) < min_hab:
        min_hab = abs(hab)
        answer = [L, R]

    # ๋‘ ์šฉ์•ก์˜ํ•ฉ์ด 0๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ์™ผ์ชฝ์˜ ๊ฐ’์„ ๋Š˜๋ ค 0์— ๊ฐ€๊น๊ฒŒ
    if hab < 0:
        left += 1
    # ๋ฐ˜๋Œ€๋กœ, ๋‘ ์šฉ์•ก์˜ ํ•ฉ์ด 0๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์˜ค๋ฅธ์ชฝ์˜ ๊ฐ’์„ ์ค„์—ฌ์„œ 0์— ๊ฐ€๊น๊ฒŒ
    else:
        right -= 1

print(answer[0], answer[1])

3. ํšŒ๊ณ 

  • left, right : ๋‘ ํฌ์ธํ„ฐ๋Š” ์–‘ ๋์—์„œ ์‹œ์ž‘ํ•œ๋‹ค.
  • min_hab : 0์— ๊ฐ€๊นŒ์šด ์ตœ์†Œํ•ฉ
    • ary์˜ ์ˆซ์ž๊ฐ€ -1,000,000,000 ์ด์ƒ 1,000,000,000 ์ดํ•˜ ๋ผ๋Š” ์กฐ๊ฑด์ด ์žˆ์œผ๋ฏ€๋กœ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ฐจ์ด์ธ 2000000001๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ค€๋‹ค.
  • ํˆฌํฌ์ธํ„ฐ ์‚ฌ์šฉ
    • ์ฃผ์–ด์ง€๋Š” ary์˜ ์ตœ๋Œ€๊ธธ์ด๊ฐ€ 100,000 ์ด๋ฏ€๋กœ ํˆฌํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด ํ‘ผ๋‹ค.
    • ๋‘ ์šฉ์•ก์˜ ํ•ฉ์ด 0๋ณด๋‹ค ์ž‘์œผ๋ฉด ๊ฐ’์„ ์กฐ๊ธˆ ๋” ๋Š˜๋ ค์„œ 0์— ๋” ๊ฐ€๊นŒ์›Œ์ง€๋Š”์ง€ ํ™•์ธํ•ด์•ผํ•˜๋ฏ€๋กœ ์™ผ์ชฝ๊ฐ’์„ ๋Š˜๋ ค์ค€๋‹ค.
    • ๋‘ ์šฉ์•ก์˜ ํ•ฉ์ด 0๋ณด๋‹ค ํฌ๋ฉด ๊ฐ’์„ ์กฐ๊ธˆ ๋” ์ค„์—ฌ์„œ 0์— ๋” ๊ฐ€๊นŒ์›Œ์ง€๋Š”์ง€ ํ™•์ธํ•ด์•ผํ•˜๋ฏ€๋กœ ๋” ํฐ ๊ฐ’์ธ ์˜ค๋ฅธ์ชฝ ๊ฐ’์„ ์ค„์—ฌ์ค€๋‹ค.
    • L๊ณผ R์˜ ํ•ฉ์˜ ์ ˆ๋Œ€๊ฐ’(0์—์„œ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์กŒ๋Š”์ง€)์™€ ๊ธฐ์กด์˜ min_hab๋ฅผ ๋น„๊ตํ•ด๊ฐ€๋ฉฐ ๊ณ„์†ํ•ด์„œ min_hab์„ ๋” ์ž‘์€ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ ํ•ด์ค€๋‹ค.
      • ๊ทธ๋•Œ๋งˆ๋‹ค ์›์†Œ์˜ ๊ฐ’์„ answer์— ์—…๋ฐ์ดํŠธ ํ•˜๋‹ค๊ฐ€ left < right๊ฐ€ ์•„๋‹Œ ์ˆœ๊ฐ„์— ์ข…๋ฃŒํ•˜๊ณ  ์ •๋‹ต์„ ์ถœ๋ ฅํ•œ๋‹ค.

4. ์ฐธ๊ณ 

https://bladejun.tistory.com/97