码迷,mamicode.com
首页 > 其他好文 > 详细

石子合并(区间dp)

时间:2020-02-24 22:40:11      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:new   tin   put   win   ++   string   bsp   using   OWIN   

石子合并不应该是个区间dp?

题目:There is an old stone game.At the beginning of the game the player picks n(1<=n<=50000) piles of stones in a line. The goal is to merge the stones in one pile observing the following rules:
At each step of the game,the player can merge two adjoining piles to a new pile.The score is the number of stones in the new pile.
You are to write a program to determine the minimum of the total score.

Input

The input contains several test cases. The first line of each test case contains an integer n, denoting the number of piles. The following n integers describe the number of stones in each pile at the beginning of the game.
The last test case is followed by one zero.

Output

For each test case output the answer on a single line.You may assume the answer will not exceed 1000000000.

Sample Input

1
100
3
3 4 3
4
1 1 1 1
0

Sample Output

0
17
8

n<=50000都把我看蒙了,结果一查题解是GarsiaWachs算法??

算了,就当我先没看到数据量.

和前几天讲到的能量项链做法基本类似,这个要更简单一些,因为它是个线性dp,不是个环.

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
int a[10000];
int sum[10000][10000];
int dp[10000][10000];
int main()
{
    while(cin>>n)
    {
        if(n==0)
            break;
        for(int i=1; i<=n; i++)
        {
            cin>>a[i];
        }
        if(n==1)
        {
            cout<<0<<endl;
            continue;
        }
        memset(dp,9999999,sizeof(dp));
        for(int i=1; i<=n; i++)
        {
            sum[i][i]=a[i];
            dp[i][i]=0;
            for(int j=i+1; j<=n; j++)
            {
                sum[i][j]=sum[i][j-1]+a[j];
            }
        }
        for(int i=2; i<=n; i++)
        {
            for(int j=1; j<=n-i+1; j++)
            {
                int p=j+i-1;
                for(int k=j; k<=p-1; k++)
                {
                    dp[j][p]=min(dp[j][p],dp[j][k]+dp[k+1][p]+sum[j][p]);
                }
            }

        }
        cout<<dp[1][n]<<endl;
        memset(sum,0,sizeof(sum));
    }
    return 0;
}

 

石子合并(区间dp)

标签:new   tin   put   win   ++   string   bsp   using   OWIN   

原文地址:https://www.cnblogs.com/iloveysm/p/12359137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!