https://www.acmicpc.net/problem/14607
14607번: 피자 (Large)
예제1의 입력이 1이므로, 게임 시작부터 갑이 분리할 수 있는 피자탑이 없습니다. 따라서 갑이 얻는 즐거움은 0입니다. 예제2의 정답 3은 다음과 같은 과정을 통해 얻어집니다. 먼저 놀이를 시작
www.acmicpc.net
저는 DP를 이용해 문제를 해결하였습니다.
cal(n) = n/2 * n/2 + cal(n/2) + cal(n/2) [짝수]
cal(n) = n/2 * (n+1)/2 + cal(n/2) + cal(n+1/2) [홀수]
위의 식을 이용하고 위 식을 dp를 사용하지 않으면 중복된 계산이 나오기 때문에 dp를 이용해 이를 해결하였습니다.
package BOJ.dp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class BOJ_14607 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long n = Long.parseLong(br.readLine());
Map<Long,Long> dp = new HashMap<>();
long result = cal(n, dp);
System.out.println(result);
}
private static long cal(long depth, Map<Long,Long> dp) {
if (depth == 1) {
return 0;
}
if (dp.containsKey(depth)) {
return dp.get(depth);
}
int temp = 0;
if (depth % 2 != 0) {
temp = 1;
}
long result = cal(depth / 2, dp) + cal(depth / 2 + temp, dp);
result += (depth / 2) * (depth / 2 + temp);
dp.put(depth,result);
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 29703번 펭귄의 하루 (JAVA) (1) | 2023.10.09 |
---|---|
백준 1251번 단어 나누기 (JAVA) (0) | 2023.10.08 |
백준 13699번 점화식 (JAVA) (0) | 2023.10.06 |
백준 1544번 사이클 단어 (JAVA) (0) | 2023.10.05 |
백준 22251번 빌런 호석 (JAVA) (0) | 2023.10.04 |