https://www.acmicpc.net/problem/18230
2021년, 정보대 화장실에서 물이 자꾸 범람하는 탓에 바닥 타일링을 다시 할 지경에 이르렀다. 타일링의 장인 민규는 "언제나 타일링은 예쁘게"라는 좌우명으로 살아왔다. 새로 타일링을 해야 하는 화장실 바닥은 2×N 크기의 격자로 표현이 된다. 민규에게는 2×1 크기의 타일 A개와 2×2 크기의 타일 B개가 있다. 각 타일들에는 "예쁨"의 정도가 있는데, 화장실 바닥의 예쁨은 바닥을 구성하는 타일들의 예쁨의 합이 된다. 민규는 가지고 있는 타일들을 이용해서 화장실 바닥의 예쁨이 최대로 되게 타일링 하려고 한다. 이때, 얻을 수 있는 예쁨의 최댓값은 얼마일까? 타일은 90도 회전이 가능하다.
1 ≤ N, A, B ≤ 2000
2 × B + A ≥ N
각 타일의 예쁨은 1,000,000 이하의 양의 정수
처음엔 모든 경우의 수를 찾는 방법으로 작성했는데, 시간 초과가 났다.
모든 경우의 수를 돌아도 2000 * 2000 으로 괜찮다고 생각했는데 시간 초과된 이유는 모르겠다.
우선순위 큐를 이용해서 가장 예쁨 지수가 높은 타일부터 사용하는 방식으로 풀었다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
StringTokenizer st2 = new StringTokenizer(br.readLine(), " ");
br.close();
int n = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken());
PriorityQueue<Integer> aQueue = new PriorityQueue(Collections.reverseOrder());
for (int i = 0; i < a; i++) {
aQueue.add(Integer.valueOf(st1.nextToken()));
}
int b = Integer.parseInt(st.nextToken());
PriorityQueue<Integer> bQueue = new PriorityQueue(Collections.reverseOrder());
for (int i = 0; i < b; i++) {
bQueue.add(Integer.valueOf(st2.nextToken()));
}
solution(n, aQueue, bQueue);
}
private static void solution(int n, PriorityQueue<Integer> aQueue, PriorityQueue<Integer> bQueue) {
long sum = 0;
//n 홀수면 길이 1만큼 채우고 시작
if (n % 2 == 1) {
n--;
sum = aQueue.poll();
}
//모든 길이 채울 때까지 반복
while (n != 0) {
n -= 2; //매번 타일을 2의 길이만큼 채운다
//가로 길이 1짜리 타일이 1개 이하로 남은 경우, 가로 길이 2짜리 1개 붙이기
if (aQueue.size() < 2) {
sum += bQueue.poll();
continue;
}
//가로 길이 2짜리 타일이 없는 경우, 가로 길이 1짜리 2개 붙이기
if (bQueue.isEmpty()) {
sum += aQueue.poll() + aQueue.poll();
continue;
}
Integer a1 = aQueue.poll();
Integer a2 = aQueue.poll();
Integer b = bQueue.poll();
//가로 길이 1짜리 2개 붙이는 경우, 가로 길이 1짜리 타일만 큐에서 제거
if (a1 + a2 > b) {
bQueue.add(b);
sum += a1 + a2;
continue;
}
//가로 길이 2짜리 1개 붙이는 경우, 가로 길이 2짜리 타일만 큐에서 제거
aQueue.add(a1);
aQueue.add(a2);
sum += b;
}
System.out.println(sum);
}
}