Skip to content

Commit 470e512

Browse files
committed
[Gold IV] Title: 수 묶기, Time: 8 ms, Memory: 79512 KB -BaekjoonHub
1 parent 0a5183a commit 470e512

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# [Gold IV] 수 묶기 - 1744
2+
3+
[문제 링크](https://www.acmicpc.net/problem/1744)
4+
5+
### 성능 요약
6+
7+
메모리: 79512 KB, 시간: 8 ms
8+
9+
### 분류
10+
11+
그리디 알고리즘, 정렬, 많은 조건 분기
12+
13+
### 제출 일자
14+
15+
2025년 6월 15일 14:11:36
16+
17+
### 문제 설명
18+
19+
<p>길이가 N인 수열이 주어졌을 때, 그 수열의 합을 구하려고 한다. 하지만, 그냥 그 수열의 합을 모두 더해서 구하는 것이 아니라, 수열의 두 수를 묶으려고 한다. 어떤 수를 묶으려고 할 때, 위치에 상관없이 묶을 수 있다. 하지만, 같은 위치에 있는 수(자기 자신)를 묶는 것은 불가능하다. 그리고 어떤 수를 묶게 되면, 수열의 합을 구할 때 묶은 수는 서로 곱한 후에 더한다.</p>
20+
21+
<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>
22+
23+
<p>수열의 모든 수는 단 한번만 묶거나, 아니면 묶지 않아야한다.</p>
24+
25+
<p>수열이 주어졌을 때, 수열의 각 수를 적절히 묶었을 때, 그 합이 최대가 되게 하는 프로그램을 작성하시오.</p>
26+
27+
### 입력
28+
29+
<p>첫째 줄에 수열의 크기 N이 주어진다. N은 50보다 작은 자연수이다. 둘째 줄부터 N개의 줄에 수열의 각 수가 주어진다. 수열의 수는 -1,000보다 크거나 같고, 1,000보다 작거나 같은 정수이다.</p>
30+
31+
### 출력
32+
33+
<p>수를 합이 최대가 나오게 묶었을 때 합을 출력한다. 정답은 항상 2<sup>31</sup>보다 작다.</p>
34+
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import Foundation
2+
3+
class FileIO {
4+
@inline(__always) private var buffer: [UInt8] = Array(FileHandle.standardInput.readDataToEndOfFile()) + [0], byteIdx = 0
5+
6+
@inline(__always) private func readByte() -> UInt8 {
7+
defer { byteIdx += 1 }
8+
return buffer.withUnsafeBufferPointer { $0[byteIdx] }
9+
}
10+
11+
@inline(__always) func readInt() -> Int {
12+
var number = 0, byte = readByte(), isNegative = false
13+
while byte == 10 || byte == 32 { byte = readByte() }
14+
if byte == 45 { byte = readByte(); isNegative = true }
15+
while 48...57 ~= byte { number = number * 10 + Int(byte - 48); byte = readByte() }
16+
return number * (isNegative ? -1 : 1)
17+
}
18+
}
19+
20+
let io = FileIO()
21+
22+
let n = io.readInt()
23+
var negas = [Int]()
24+
var posits = [Int]()
25+
for i in 0..<n {
26+
let a = io.readInt()
27+
if a < 1 {
28+
negas.append(a)
29+
continue
30+
}
31+
posits.append(a)
32+
}
33+
negas.sort { $0 > $1 }
34+
posits.sort { $0 < $1 }
35+
var answer = 0
36+
37+
while posits.count >= 2 {
38+
let a = posits.removeLast()
39+
let b = posits.removeLast()
40+
if b == 1 {
41+
answer += (a+b)
42+
continue
43+
}
44+
answer += a*b
45+
}
46+
47+
while negas.count >= 2 {
48+
let a = negas.removeLast()
49+
let b = negas.removeLast()
50+
if a*b <= a+b { break }
51+
answer += a*b
52+
}
53+
answer += posits.reduce(0, +)
54+
answer += negas.reduce(0, +)
55+
print(answer)

0 commit comments

Comments
 (0)