zoukankan      html  css  js  c++  java
  • 51Nod 1021 石子归并(区间dp经典入门)

    题意:

    N堆石子摆成一条线。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。

     n<=100

    思路:

    dp[i][j]表示以i开头,长度为j的石子合并的答案

    dp[i][j] = min(dp[i][k] + dp[i+k][j-k], dp[i][j] + sum(i,i+j-1));

    代码:

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cmath>
    #include<cstring>
    #include<string>
    #include<stack>
    #include<queue>
    #include<deque>
    #include<set>
    #include<vector>
    #include<map>
    #include<functional>
    #include<list>
        
    #define fst first
    #define sc second
    #define pb push_back
    #define mem(a,b) memset(a,b,sizeof(a))
    #define lson l,mid,root<<1
    #define rson mid+1,r,root<<1|1
    #define lc root<<1
    #define rc root<<1|1
    #define lowbit(x) ((x)&(-x)) 
    
    using namespace std;
    
    typedef double db;
    typedef long double ldb;
    typedef long long ll;
    typedef long long LL;
    typedef unsigned long long ull;
    typedef pair<int,int> PI;
    typedef pair<ll,ll> PLL;
    
    const db eps = 1e-6;
    const int mod = 1e9+7;
    const int maxn = 2e6+100;
    const int maxm = 2e6+100;
    const int inf = 0x3f3f3f3f;
    //const db pi = acos(-1.0);
    const int N = maxn;
    
    int n;
    int dp[100][100];
    int a[maxn];
    int s[maxn];
    int main(){
        int n;
        scanf("%d", &n);
        mem(dp,inf);
        for(int i = 1; i <= n; i++){
            scanf("%d", &a[i]);
            dp[i][1] = 0;
            s[i] = s[i-1]+a[i];
        }
        for(int j = 1; j <= n; j++){
            for(int i = 1; i+j-1 <= n; i++){
                for(int k = 1; k < j; k++){
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[i+k][j-k]+s[i+j-1]-s[i-1]);
                }
                //printf("%d %d %d
    ",i,j,dp[i][j]);
            }
        }
        printf("%d",dp[1][n]);
        return 0;
    } 
    
    /*`
    10
    59 -17 5 67 87 50 -71 54 27 -10
     */
  • 相关阅读:
    Spring Boot → 08:嵌入式Servlet容器自定义
    Spring Boot → 09:使用外置Servlet容器_tomcat9.0
    Spring Boot → 07:错误处理机制
    Spring Boot → 06:项目实战-账单管理系统
    Spring Boot → 05:Web开发
    zzz Objective-C的消息传递机制
    Objective-C中的SEL、IMP和Class类型(转)
    zzzObjective-C的动态特性
    zzz KVC/KVO原理详解及编程指南
    zzzzz iOS绘图教程
  • 原文地址:https://www.cnblogs.com/wrjlinkkkkkk/p/10603979.html
Copyright © 2011-2022 走看看