알고리즘

백준 14607번 피자 (JAVA)

박카스마시며코딩 2023. 10. 7. 18:41

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;
    }
}