题解 | 【模板】区间dp

def solve():
    # Read input
    n = int(input())

    # Handle special case when n=1
    if n == 1:
        print(0)
        return

    # Read array elements
    a = [0] + list(map(int, input().split()))

    # Calculate prefix sums
    sum_arr = [0] * (n + 1)
    for i in range(1, n + 1):
        sum_arr[i] = sum_arr[i - 1] + a[i]

    # Initialize dp array
    dp = [[0] * (n + 1) for _ in range(n + 1)]

    # Initialize base cases for adjacent pairs
    for i in range(1, n):
        dp[i][i + 1] = a[i] + a[i + 1]

    # Fill dp array
    for length in range(2, n):
        for left in range(1, n - length + 1):
            right = left + length
            min_cost = float("inf")

            # Try all possible splits between left and right
            for j in range(left, right):
                cost = dp[left][j] + dp[j + 1][right]
                min_cost = min(min_cost, cost)

            # Add the cost of combining all elements in the range
            dp[left][right] = min_cost + (sum_arr[right] - sum_arr[left - 1])

    # Print result
    print(dp[1][n])


solve()

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 13:15
点赞 评论 收藏
分享
鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
07-05 16:23
门头沟学院 Java
mengnankk:我投了300,约了5 6个面试。感觉项目写的太多了。一个项目就写五六个亮点,不是把整个项目的功能描述下。其他的没啥,简历看起来有点长
点赞 评论 收藏
分享
合不合适,我自己说了才算
码农索隆:hr:“真执着啊,来我公司当法人吧”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务