The typical example of interval dynamic programming is the aggregation of stones, and the realization of interval motion by using memory search is a relatively easy way to avoid some boundary judgments when the loop array is implemented.
n heap of stones arranged into a line, we can merge the adjacent two piles of stones, the cost of the merger will be consumed for the sum of the quality of the two heaps of stone, ask the minimum combined cost
The state transition equation is easy to give:
F[i][j]=min (f[i][j],f[i][k]+f[k+1][j]+sum[i][j])
Because to calculate intervals and to consider prefixes and preprocessing
Then we give the code implemented in the form of a memory search, where the memory search form can be used as a template for subsequent problems.
1#include <iostream>2#include <cstring>3#include <algorithm>4 using namespacestd;5 Const intinf=0x7fffffff;6 Const intmaxn= the;7 intN;8 intW[MAXN];9 intG[MAXN];//Prefixes andTen intF[MAXN][MAXN]; One intDfsintLintR) A { - if(L==R)return 0; - if(f[l][r]!=INF) the returnF[l][r]; - inttmp=INF; - for(inti=l;i<r;i++) -Tmp=min (Tmp,dfs (l,i) +dfs (i+1, R) +g[r]-g[l-1]); + if(tmp<F[l][r]) -f[l][r]=tmp; + returnF[l][r]; A } at intMain () - { -Cin>>N; - for(intI=1; i<=n;i++) - { -Cin>>W[i]; ing[i]=g[i-1]+W[i]; - } toMemset (F,127,sizeof(f)); +Cout<<dfs (1, N) <<Endl; - return 0; the}
This question is still quite obvious, and we are considering another problem, that is, circular dynamic programming
In fact, the annular dynamic planning is also interval type, but the interval end-to-end
It is not easy to use a memory search to implement this
A typical example is an energy necklace.
The state transition equation is given first:
F[i][j]=max (F[i][j],f[i][k]+f[k][j]+a[i]*a[j]*a[k])
Because the value of each interval problem is not the same, the different optimization forms may be used, the direct calculation can be
Then we give a fixed format that is implemented using loop array, and all the interval dynamic programming can take this form to realize
1#include <iostream>2#include <cstring>3 using namespacestd;4 Const intmaxn=1005;5 intN;6 intA[MAXN];7 Long Longans=0;8 intF[MAXN][MAXN];9 voidDP ()Ten { One for(intL=2; l<=n;l++)//interval Length A for(intI=1; i<=n*2-l+1; i++)//interval Start - { - intJ=i+l;//interval end point the for(intk=i+1; k<=j-1; k++)//any point in the interval -F[i][j]=max (f[i][j],f[i][k]+f[k][j]+a[i]*a[j]*a[k]); - } - for(intI=1; i<=n;i++) + if(ans<f[i][i+N]) -ans=f[i][i+n]; + } A intMain () at { -Cin>>N; - for(intI=1; i<=n;i++) - { -Cin>>A[i]; -a[n+i]=A[i]; in } - DP (); tocout<<ans; + return 0; -}
The length of the interval is enumerated separately, the beginning of the interval and any point in the interval is good.
Realization of memory search and cyclic array for dynamic programming of interval type