[Gold IV] Title: 수 묶기, Time: 60 ms, Memory: 38092 KB -BaekjoonHub

This commit is contained in:
SSUM
2025-02-14 18:11:05 +09:00
parent f981c75e07
commit dded0ec6f2
2 changed files with 91 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
# [Gold IV] 수 묶기 - 1744
[문제 링크](https://www.acmicpc.net/problem/1744)
### 성능 요약
메모리: 38092 KB, 시간: 60 ms
### 분류
많은 조건 분기, 그리디 알고리즘, 정렬
### 제출 일자
2025년 2월 14일 18:10:54
### 문제 설명
<p>길이가 N인 수열이 주어졌을 때, 그 수열의 합을 구하려고 한다. 하지만, 그냥 그 수열의 합을 모두 더해서 구하는 것이 아니라, 수열의 두 수를 묶으려고 한다. 어떤 수를 묶으려고 할 때, 위치에 상관없이 묶을 수 있다. 하지만, 같은 위치에 있는 수(자기 자신)를 묶는 것은 불가능하다. 그리고 어떤 수를 묶게 되면, 수열의 합을 구할 때 묶은 수는 서로 곱한 후에 더한다.</p>
<p>예를 들면, 어떤 수열이 {0, 1, 2, 4, 3, 5}일 때, 그냥 이 수열의 합을 구하면 0+1+2+4+3+5 = 15이다. 하지만, 2와 3을 묶고, 4와 5를 묶게 되면, 0+1+(2*3)+(4*5) = 27이 되어 최대가 된다.</p>
<p>수열의 모든 수는 단 한번만 묶거나, 아니면 묶지 않아야한다.</p>
<p>수열이 주어졌을 때, 수열의 각 수를 적절히 묶었을 때, 그 합이 최대가 되게 하는 프로그램을 작성하시오.</p>
### 입력
<p>첫째 줄에 수열의 크기 N이 주어진다. N은 50보다 작은 자연수이다. 둘째 줄부터 N개의 줄에 수열의 각 수가 주어진다. 수열의 수는 -1,000보다 크거나 같고, 1,000보다 작거나 같은 정수이다.</p>
### 출력
<p>수를 합이 최대가 나오게 묶었을 때 합을 출력한다. 정답은 항상 2<sup>31</sup>보다 작다.</p>

View File

@@ -0,0 +1,57 @@
import heapq
import sys
from collections import deque
input = sys.stdin.readline
maxheap=[]
minheap=[]
result = 0
count_0 = 0
count_1 = 0
N = int(input().rstrip())
def plusnum(num):
maxheap.append(num)
def minusnum(num):
minheap.append(num)
for i in range(N):
num = int(input().rstrip())
if(num==0):
count_0 += 1
elif(num==1):
count_1 += 1
elif(num>0):
plusnum(num)
else:
minusnum(num)
maxheap.sort()
minheap.sort()
while maxheap:
first_value = maxheap.pop()
if maxheap:
second_value = maxheap.pop()
result += (first_value * second_value)
else:
result += first_value
if (len(minheap)%2==1):
if count_0 and minheap:
minheap.pop()
else:
result+=minheap.pop()
while minheap:
first_value = minheap.pop()
second_value = minheap.pop()
result += (first_value * second_value)
result+=count_1
print(result)