Cattle cargo passenger network grouping 60 points (advance fee DP)

Expenses in advance of DP

Because out of practice is monotonous stack optimized DP, relatively unpopular, and the complexity is still a mystery, so I chose Gugu Gu

Talk about 60 minutes \ (O (n ^ 2) \) approach

The cost in advance, more often than not refers to pre-calculate the cost to maintain the optimal substructure property DP. Instead, it destroys the nature of the sub-optimal structure , except for the last answer we need, other DP out of the answers are wrong. So the question than we think ahead of its greatest contribution when the n-== i , leading to the final answer except dp [n] is correct, the rest are wrong .

In other words, the cost in advance in case of a sub-optimal structure of the equation does not meet the DP, we only need to answer a certain point, we consider the contribution of the previous state of the individual points, so as to achieve the effect of ignoring the after-effect , or common segment DP and DP interval optimization

Look \ (O (n ^ 3) \) of the DP equation:

\(f[n][m]=min{f[n-1][k]+m∗(s(m)−s(k))+max(m,k+1)−min(m,k+1)}\)

Where s denotes the prefix and

Consider again \ (O (N ^ 2) \) of the DP, is calculated considering direct \ (dp [n] \)

To not consider the impact of the maximum minimum, we found

\(dp[n]=1*(s[a]-s[0])+2*(s[b]-s[a])+...+i*(s[n]-s[c])\)

Simplification available

\(dp[n]=-s[0]-s[a]-s[b]-...-s[c]+i*s[n]\)

It can also be written as

\(dp[n]=-s[0]+s[n]-s[a]+s[n]-s[b]+s[n]-...-s[c]+s[n]-s[n]+s[n]\)

Therefore, each \ (dp [i] \) contribution to the final answer is \ (S [n-] -s [I] \) , and then consider the influence brought by the minimum and maximum values to the DP

\(dp[i]=min(dp[i],dp[j-1]+max(j,i)-min(j,i)+s[n]-s[i])\)

\(dp[0]=s[n]\)

Code

#include<bits/stdc++.h>
//#pragma GCC optimize(3)
//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast")
using namespace std;

#define go(i,a,b) for(int i=a;i<=b;++i)
#define com(i,a,b) for(int i=a;i>=b;--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define fo(i,a) for(int i=0;i<a;++i)
#define int long long
#define il inline
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))

const int inf=0x3f3f3f3f3f3f3f3f,N=1e5+10;

int n,m,a[N],dp[N],g[N],sum[N];

il void read(int &x){
    x=0;char c=getchar(),f=1;
    while(!isdigit(c)){ if(c=='-') f=-1; c=getchar(); }
    while(isdigit(c)){ x=x*10+c-'0'; c=getchar(); }
    x*=f;
}

signed main(){
    //freopen("input.txt","r",stdin);
    read(n),read(m);
    go(i,1,n) read(a[i]);
    go(i,1,n) sum[i]=sum[i-1]+a[i];
    mem(dp,0x3f);
    dp[0]=sum[n];
    int tot,mx,mn;
    go(i,1,n){
        tot=0,mx=0,mn=inf;
        com(j,i,1){
            tot+=a[j];
            mx=max(mx,a[j]),mn=min(mn,a[j]);
            if(tot>m) break;
            dp[i]=min(dp[i],dp[j-1]+mx-mn);
        }
        dp[i]+=sum[n]-sum[i];
    }
    printf("%lld",dp[n]);
    return 0;
}

Guess you like

Origin www.cnblogs.com/White-star/p/11789445.html