UVA-10891 Game of Sum 博弈 区间Dp Python

一、题意

This is a two player game. Initially there are n integer numbers in an array and players A and B get chance to take them alternatively. Each player can take one or more numbers from the left or right end of the array but cannot take from both ends at a time. He can take as many consecutive numbers as he wants during his time. The game ends when all numbers are taken from the array by the players. The point of each player is calculated by the summation of the numbers, which he has taken. Each player tries to achieve more points from other. If both players play optimally and player A starts the game then how much more point can player A get than player B?

给n个数字,现在2个人要取数字,每次可以从队首或队尾连续取一段。求2个人取的数字最大的差值

设dp[i][j]为第一个人从i取到j的最大值,那么枚举一个插板k,则显然有转移dp[i][j]=sum[j]-sum[i-1]-min(dp[i][k-1],dp[k][j])

二、Code

while True:
    n = int(input())
    if n == 0:break
    a = list(map(int,input().split()))
    dp = [[0]*(n+5)for i in range(n+5)]
    s = [0]*(n+5)
    dp[0][0]=a[0]
    for i in range(1,n+1):
        dp[i][i] = a[i-1]
        s[i]=s[i-1]+a[i-1]
    # 枚举长度
    for len in range(1,n):
        for i in range(1,n-len+1):
            j = i + len
            mi = 0
            for k in range(i+1,j+1):
                mi=min(mi,dp[i][k-1],dp[k][j])
            dp[i][j]=s[j]-s[i-1]-mi
    print(2*dp[1][n]-s[n])

 

你可能感兴趣的:(ACM代码)