QBXT2018 5 2 DP & Graph Theory Class Memory Search --- Simple DP Algorithm

For some students who have just learned DP, it is somewhat difficult to directly write the DP transfer equation. Here Zhang Haowei (Zhang Guoyi) dalao taught us an easy way. You can write a simple brute force search first, and then turn it into a memoized search.

Advantages: The idea is simple.

Disadvantages: The code is slightly harder to write and hard to optimize.

Example: 01 Knapsack Problem

The most violent approach can be written first, which is to enumerate each item to choose or not to choose.

void dfs( int x, int y, int z) //x= current item number, y=sum of current volume, z=sum of current value 
{
   if (x==n+ 1 )
  {
    if (y<=m) ans=max(ans,z);
    return;
  }
  dfs(x+1,y+w[x],z+v[x]);
  dfs(x+1,y,z);
}
dfs(1,0,0);
The time complexity is O( 2 ^n)

It can be observed that when x and y are fixed, larger z is better.

Consider xy as state z as the value represented by the state. That is, dp[x][y]=z. Then change the return value of DFS to int.

int dfs(int x,int y){
    if(y>t) return -inf;
    if(x==n+1){
        return 0;
    }
    if(dp[x][y]) return dp[x][y];
    dp[x][y]=max(dfs(x+1,y),dfs(x+1,y+w[x])+v[x]);
    return dp[x][y];
}

x=current item number y=sum of current volume dp[x][y]= maximum value that can be obtained next t=backpack volume.

Since the case of y>t is obviously illegal, dp[x][y](y>t)= -inf   ie this case will never be the optimal answer.

If(x==n+1) the recursive boundary can get 0 next value, so it returns 0.

if(dp[x][y]) shows that this situation has been traversed before. Because the status of the question will not change due to the difference in DFS, that is, both DFS(3, 2) and DFS(3, 4) may traverse to the current situation, but they will not be different due to the difference in DFS, so you can return directly The value when it was traversed before.

dp[x][y]=max(dfs(x+ 1,y),dfs(x+ 1,y+w[x])+ v[x]); There are two decisions: choose or not, so dp[ x][y] will transfer the above two values ​​to. It should be noted that dp[][] represents the maximum value that can be obtained next, so don't forget to add the current contribution.

This is memoized search.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325170935&siteId=291194637