목차

동전 게임

ps
링크acmicpc.net/…
출처BOJ
문제 번호6000
문제명동전 게임
레벨플래티넘 3
분류

게임 이론

시간복잡도O(n^2)
인풋사이즈n<=2000
사용한 언어Python 3.11
제출기록57508KB / 304ms
최고기록304ms
해결날짜2023/07/05

풀이

코드

코드 1 - 메모리 커팅 없음. pypy에서만 통과

"""Solution code for "BOJ 6000. 동전 게임".

- Problem link: https://www.acmicpc.net/problem/6000
- Solution link: http://www.teferi.net/ps/problems/boj/6000

Tags: [game theory]
"""

import sys

INF = float('inf')


def main():
    N = int(sys.stdin.readline())
    C = [int(sys.stdin.readline()) for _ in range(N)]

    max_score = [[None] * (N + 1) for _ in range(N + 1)]
    max_score[0][0] = 0
    coin_sum = 0
    for i in range(1, N + 1):
        coin_sum += C[-i]
        min_max_score = INF
        for k in range(1, i + 1):
            opponent_max_score = max_score[i - k][min(i - k, k * 2)]
            if opponent_max_score < min_max_score:
                min_max_score = opponent_max_score
            max_score[i][k] = coin_sum - min_max_score

    print(max_score[N][2])


if __name__ == '__main__':
    main()

코드 2 - 메모리 커팅. python에서도 통과

"""Solution code for "BOJ 6000. 동전 게임".

- Problem link: https://www.acmicpc.net/problem/6000
- Solution link: http://www.teferi.net/ps/problems/boj/6000

Tags: [game theory]
"""

import sys

INF = float('inf')


def main():
    def get_max_score(n, k):
        if k * 3 >= n:
            return max(max_score[n][-1], psum[n] - psum[n - k])
        else:
            return max_score[n][k]

    N = int(sys.stdin.readline())
    C = [int(sys.stdin.readline()) for _ in range(N)]
    psum = [v := 0] + [v := v + x for x in reversed(C)]

    max_score = [[0] for _ in range(N + 1)]
    coin_sum = 0
    for i in range(1, N + 1):
        coin_sum += C[-i]
        min_max_score = INF
        for k in range(1, i // 3 + 1):
            opponent_max_score = get_max_score(i - k, k * 2)
            if opponent_max_score < min_max_score:
                min_max_score = opponent_max_score
            max_score[i].append(coin_sum - min_max_score)

    print(get_max_score(N, 2))


if __name__ == '__main__':
    main()