15903번: 카드 합체 놀이
첫 번째 줄에 카드의 개수를 나타내는 수 n(2 ≤ n ≤ 1,000)과 카드 합체를 몇 번 하는지를 나타내는 수 m(0 ≤ m ≤ 15×n)이 주어진다. 두 번째 줄에 맨 처음 카드의 상태를 나타내는 n개의 자연수 a1,
www.acmicpc.net
사용한 숫자로 다시 새로운 숫자를 만들어 사용해야 하고, 카드의 구성이 지속적으로 바뀌기 때문에 우선순위 큐를 사용해서 가장 작은 카드 두장을 계속 합해가면 풀 수 있습니다.
문제코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class boj15903_2 {
public long solution() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer infoToken = new StringTokenizer(br.readLine());
int cardCount = Integer.parseInt(infoToken.nextToken());
int actions = Integer.parseInt(infoToken.nextToken());
StringTokenizer cardToken = new StringTokenizer(br.readLine());
PriorityQueue<Long> smallestCards = new PriorityQueue<>();
for (int i = 0; i < cardCount; i++) {
smallestCards.offer(Long.parseLong(cardToken.nextToken()));
}
// 두개의 숫자를 뽑아서 합한 뒤
// 다시 우선순위 큐에 두번 넣어준다.
for (int i = 0; i < actions; i++) {
long first = smallestCards.poll();
long second = smallestCards.poll();
smallestCards.offer(first+second);
smallestCards.offer(first+second);
}
// 정답을 구한다.
long answer = 0;
while (!smallestCards.isEmpty()){
answer += smallestCards.poll();
}
return answer;
}
public static void main(String[] args) throws IOException {
System.out.println(new boj15903_2().solution());
}
}
결과
입력
4 2
4 2 3 1
출력
19
'Algorithm' 카테고리의 다른 글
백준 11000 강의실 배정 (0) | 2023.07.14 |
---|---|
백준 7662 이중 우선순위 큐 (0) | 2023.07.14 |
백준 2447 별찍기10 (0) | 2023.07.12 |
백준 17829 222-풀링 (0) | 2023.07.12 |
이진 탐색 알고리즘 (0) | 2023.07.11 |