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;
    }
  • 相关阅读:
    Zk学习笔记——权限控制
    guava学习笔记
    Elasticsearch学习笔记——别名
    Kafka学习笔记——存储结构
    分布式协议——Paxos、Raft和ZAB
    图解 Java 中的数据结构及原理!
    牛逼哄哄的 Lambda 表达式,简洁优雅就是生产力!
    你必须了解Spring的生态
    盘点 35 个 Apache 顶级项目,我拜服了…
    前后端分离如何做权限控制设计?
  • 原文地址:https://www.cnblogs.com/iloveysm/p/12359137.html
Copyright © 2011-2022 走看看