์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฒด์œก๋ณต (Greedy)

ghtis1798 2021. 6. 20. 17:46

๐Ÿ”ธ ๋ฌธ์ œ ์ ‘๊ทผ ๋ฐฉ์‹

  1. ์ฒด์œก๋ณต ์—ฌ๋ฒŒ์€ ์ž์‹  ๊ธฐ์ค€ ์•ž, ๋’ค๋กœ๋งŒ ๋นŒ๋ ค์ค„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฑด ์œ ์˜
  2. ์ฒด์œก๋ณต ์—ฌ๋ฒŒ์ด ์žˆ๋Š”๋ฐ ๋„๋‚œ ๋‹นํ•œ ๊ฒฝ์šฐ๋ฅผ ๋จผ์ € ๊ณ ๋ คํ•  ๊ฒƒ. ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๋ฐœ์ƒ

๐Ÿ’ง Source code

def solution(n, lost, reserve):
    ''' ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-์ฒด์œก๋ณต ๋ฌธ์ œ ํ’€์ด (Greedy)

        Notes:
            1. ์ฒด์œก๋ณต ์—ฌ๋ฒŒ์€ ์ž์‹  ๊ธฐ์ค€ ์•ž, ๋’ค๋กœ๋งŒ ๋นŒ๋ ค์ค„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ ์ฃผ์˜
            2. ์ฒด์œก๋ณต ์—ฌ๋ฒŒ์ด ์žˆ๋Š”๋ฐ ๋„๋‚œ ๋‹นํ•œ ๊ฒฝ์šฐ๋ฅผ ๋จผ์ € ๊ณ ๋ คํ•  ๊ฒƒ. ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๋ฐœ์ƒ

        Args:
            n (int) : ํ•™์ƒ ์ˆ˜
            lost (list) : ์ฒด์œก๋ณต์„ ์žƒ์–ด๋ฒ„๋ฆฐ ํ•™์ƒ ๋ฒˆํ˜ธ๋ฅผ ๋‹ด์€ ๋ฆฌ์ŠคํŠธ
            reserve (list) : ์ฒด์œก๋ณต ์—ฌ๋ฒŒ์„ ๊ฐ€์ ธ์˜จ ํ•™์ƒ ๋ฒˆํ˜ธ๋ฅผ ๋‹ด์€ ๋ฆฌ์ŠคํŠธ

        Returns:
            answer (int) : ์ฒด์œก ์ˆ˜์—…์— ์ฐธ์—ฌํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ํ•™์ƒ ์ˆ˜
    '''

    for l in lost:
        if l in reserve:
            lost.remove(l)
            reserve.remove(l)

    answer = n - len(lost)

    for l in lost:
        for r in reserve:
            if abs(l-r) <= 1:
                answer += 1
                reserve.remove(r)
                break

    return answer

def best_solution(n, lost, reserve):
    _reserve = [r for r in reserve if r not in lost]
    _lost = [l for l in lost if l not in reserve]
    for r in _reserve:
        f = r - 1
        b = r + 1
        if f in _lost:
            _lost.remove(f)
        elif b in _lost:
            _lost.remove(b)
    return n - len(_lost)

n = int(input())
lost = list(map(int, input().split()))
reserve = list(map(int, input().split()))
print(solution(n, lost, reserve))