zoukankan      html  css  js  c++  java
  • 石子合并(区间dp)

    石子合并不应该是个区间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;
    }
  • 相关阅读:
    使用正则匹配数字
    钻石和玻璃球游戏(钻石位置不固定)
    简单绘图
    未解决问题02
    Sqlite3 实现学生信息增删改查
    【Python】科赫雪花绘制
    【Python爬虫】抖音去水印
    【MATLAB】数学计算软件 MathWorks MATLAB R2020a 中文破解版
    【C语言】用指针作为形参完成数据的升序排列
    【C语言】数组名作函数参数完成数据的升序排列
  • 原文地址:https://www.cnblogs.com/iloveysm/p/12359137.html
Copyright © 2011-2022 走看看