문제풀이/백준(Boj) 문제풀이

[백준][그리디 알고리즘] 1744. 수 묶기 (파이썬/Python)

얄루몬 2021. 10. 3. 17:06

<오답>

import sys
input = sys.stdin.readline

n = int(input())
a = []
result = []

for _ in range(n):
    a.append(int(input()))

a.sort()
for i in range(1,len(a),2):
    if a[i-1] <= 0:
        result.append(a[i-1]+a[i])
    else:
        result.append(a[i-1]*a[i])
        
print(sum(result))

# 테스트케이스를 다 넣었을 땐 정답인데 다를 땐 아닌가보다. 

 

# 아마도 1개씩 남게 되는 경우가 고려되지 않아 그런 것인가?

 

<오답 2>

import sys
input = sys.stdin.readline

n = int(input())
a = [] #0보다 큰 수
b = [] #0보다 작은 수
result = 0

for _ in range(n):
    c = int(input())
    if c > 0:
        a.append(c)
    else:
        b.append(c)

a.sort()#pop은 뒤에서부터 꺼내기 때문에 오름차순으로 정렬해줘야 함.
b.sort()

while len(a) != 0 :
    if len(a) == 1:
        result += a.pop()
    else: 
        result += a.pop()*a.pop()
        
while len(b) != 0:
    result += b.pop()

print(result)

# for문을 돌면 b의 리스트 안에 0을 남기는 바람에 while문으로 작성해도 틀렸다고 나온다..

 

<정답>

import sys
input = sys.stdin.readline

n = int(input())
a = []
b = []
result = 0
for i in range(n):
    c = int(input())
    if c == 1:
        result += 1
    elif c > 0:
        a.append(c)
    else:
        b.append(c)
a.sort()
b.sort(reverse = True)

while len(a) != 0:
    if len(a) == 1:
        result += a.pop()
    else:
        result += a.pop() * a.pop()
while len(b) != 0:
    if len(b) == 1:
        result += b.pop()
    else:
        result += b.pop() * b.pop()
print(result)

# b 정렬을 해주고(내림차순으로) 같은 형식으로 작성해주니 정답이 나온다 ㅋ .. ;