[Gold III] 파일 합치기 - 11066
성능 요약
메모리: 29556 KB, 시간: 872 ms
분류
다이나믹 프로그래밍(dp)
문제 설명
소설가인 김대전은 소설을 여러 장(chapter)으로 나누어 쓰는데, 각 장은 각각 다른 파일에 저장하곤 한다. 소설의 모든 장을 쓰고 나서는 각 장이 쓰여진 파일을 합쳐서 최종적으로 소설의 완성본이 들어있는 한 개의 파일을 만든다. 이 과정에서 두 개의 파일을 합쳐서 하나의 임시파일을 만들고, 이 임시파일이나 원래의 파일을 계속 두 개씩 합쳐서 소설의 여러 장들이 연속이 되도록 파일을 합쳐나가고, 최종적으로는 하나의 파일로 합친다. 두 개의 파일을 합칠 때 필요한 비용(시간 등)이 두 파일 크기의 합이라고 가정할 때, 최종적인 한 개의 파일을 완성하는데 필요한 비용의 총 합을 계산하시오.
예를 들어, C1, C2, C3, C4가 연속적인 네 개의 장을 수록하고 있는 파일이고, 파일 크기가 각각 40, 30, 30, 50 이라고 하자. 이 파일들을 합치는 과정에서, 먼저 C2와 C3를 합쳐서 임시파일 X1을 만든다. 이때 비용 60이 필요하다. 그 다음으로 C1과 X1을 합쳐 임시파일 X2를 만들면 비용 100이 필요하다. 최종적으로 X2와 C4를 합쳐 최종파일을 만들면 비용 150이 필요하다. 따라서, 최종의 한 파일을 만드는데 필요한 비용의 합은 60+100+150=310 이다. 다른 방법으로 파일을 합치면 비용을 줄일 수 있다. 먼저 C1과 C2를 합쳐 임시파일 Y1을 만들고, C3와 C4를 합쳐 임시파일 Y2를 만들고, 최종적으로 Y1과 Y2를 합쳐 최종파일을 만들 수 있다. 이때 필요한 총 비용은 70+80+150=300 이다.
소설의 각 장들이 수록되어 있는 파일의 크기가 주어졌을 때, 이 파일들을 하나의 파일로 합칠 때 필요한 최소비용을 계산하는 프로그램을 작성하시오.
입력
프로그램은 표준 입력에서 입력 데이터를 받는다. 프로그램의 입력은 T개의 테스트 데이터로 이루어져 있는데, T는 입력의 맨 첫 줄에 주어진다.각 테스트 데이터는 두 개의 행으로 주어지는데, 첫 행에는 소설을 구성하는 장의 수를 나타내는 양의 정수 K (3 ≤ K ≤ 500)가 주어진다. 두 번째 행에는 1장부터 K장까지 수록한 파일의 크기를 나타내는 양의 정수 K개가 주어진다. 파일의 크기는 10,000을 초과하지 않는다.
출력
프로그램은 표준 출력에 출력한다. 각 테스트 데이터마다 정확히 한 행에 출력하는데, 모든 장을 합치는데 필요한 최소비용을 출력한다.
풀이
dp는 왜이렇게 혼자 생각하기가 힘든걸까......
점화식만 찾으면 풀리는건데 점화식 찾기가 너무 힘들다 하하하
https://www.acmicpc.net/board/view/53172
이 글에서 도움을 많이 얻었다.
파일 두 개를 합치는 비용은 항상 같다.
파일 세 개를 합치는 비용은
A + (B+C), (A+B)+C, 두 가지 중 더 작은 값을 찾아야 한다.
여기서 실제 비용은 (B+C) + (A+(B+C))가 되기 때문에, 처음 합칠 때의 값이 가장 작은 경우를 계속해서 찾아야 한다.
처음에는 dp를 재귀로 구현하려고 했는데, 시간 초과가 났다.
그래서 반복문으로 파일의 간격이 2인 경우(합칠 파일이 3개인 경우)부터 증가시키며 dp를 적용하였다.
N개의 파일을 합칠 때의 최소 비용은 (1,i)까지 합치는 비용 + (i+1,N)까지 합치는 비용이 가장 작은 값을 찾는 것과 같다.
두 파일을 나눌 때의 경계선을 어디로 잡는지가 중요한 문제였다.
package BOJ.Gold.g3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class BOJ_11066_파일합치기 {
static int N;
static int[] arr;
static int[] total;
static int[][] dp;
static int INF = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
while (T-- > 0) {
N = Integer.parseInt(br.readLine());
arr = new int[N + 1];
total = new int[N + 1];
StringTokenizer st = new StringTokenizer(br.readLine());
dp = new int[N + 1][N + 1];
for (int i = 1; i <= N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
total[i] = total[i - 1] + arr[i]; // 누적합
}
for (int i = 1; i < N; i++)
dp[i][i + 1] = arr[i] + arr[i + 1]; // 인접한 두개는 각각의 값 그대로
for (int gap = 2; gap < N; gap++) {
for (int i = 1; i + gap <= N; i++) {
int j = i + gap;
dp[i][j] = INF;
for (int k = i; k < j; k++)
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j]);
dp[i][j] += total[j] - total[i - 1];
}
}
sb.append(dp[1][N]).append("\n");
}
System.out.print(sb);
}
static int find(int st, int ed) {
if (dp[st][ed] != INF) return dp[st][ed];
if (st == ed) return dp[st][ed] = arr[st];
// 이전과정의 합을 더해주기
int sum = total[ed] - total[st - 1];
if (st + 1 == ed) return dp[st][ed] = arr[st] + arr[ed] + sum; // 인접한 경우는 그냥 더하기
for (int i = st; i < ed; i++) {
dp[st][ed] = Math.min(dp[st][ed], find(st, i) + find(i + 1, ed) + sum);
}
return dp[st][ed];
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 12015 - 가장 긴 증가하는 부분 수열 2 (자바 Java) (0) | 2022.10.25 |
---|---|
[백준] 1520 - 내리막 길 (자바 Java) (0) | 2022.10.24 |
[백준] 7579 - 앱 (자바 Java) (0) | 2022.10.21 |
[백준] 17244 - 아맞다우산 (자바 Java) (0) | 2022.10.21 |
[백준] 9466 - 텀 프로젝트 (자바 Java) (0) | 2022.10.17 |