Elephant and mouse DP

Elephant and mouse DP

\ (N * M \) of the trellis diagram, the lattice \ ((i, j) \ ) have \ (A_ {i, j} \) a rat, from the upper left corner as small Q \ ((1,1) \ ) went to the bottom right corner of \ ((N, M) \ ) minimal mouse to see. Mice can be seen as small, if and only if the mouse position \ ((x2, y2) \ ) satisfies \ (| X1-X2 | + | Y1-Y2 | \ LE1 of \) .

DP a more interesting question, it is quite simple. We found that if the direct setting \ (f [i] [j ] \) running causes some lattice repeated calculations, we can set \ (f [i] [j ] [0] \) represents the position \ ((I, J) \) number at least when seen in mice, and the current state of the transfer comes from above , \ (F [I] [J] [. 1] \) represents the position \ ((i, j) \ ) when minimum number of mice to see, and the current state of the transfer comes from the left, so that we can get all the conditions required for decision making, in order to avoid double counting.

Figure write like watching a transition equation

//f[i][j][0]当前状态从上面转移而来
f[i][j][0]=min(f[i-1][j][1]+mp[i][j+1]+mp[i+1][j], f[i][j][0]);
f[i][j][0]=min(f[i-1][j][0]+mp[i+1][j]+mp[i][j-1]+mp[i][j+1], f[i][j][0]);
//f[i][j][0]当前状态从左面转移而来
f[i][j][1]=min(f[i][j-1][1]+mp[i][j+1]+mp[i-1][j]+mp[i+1][j], f[i][j][1]);
f[i][j][1]=min(f[i][j-1][0]+mp[i][j+1]+mp[i+1][j], f[i][j][1]);

Complete code:

#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 1010
using namespace std;
int f[MAXN][MAXN][2],mp[MAXN][MAXN];
int n,m;
int calc(int x, int y){
    int res=0;
    if(x+1>=1&&x+1<=n) res+=mp[x+1][y];
    if(x-1>=1&&x-1<=n) res+=mp[x-1][y];
    if(y+1>=1&&y+1<=m) res+=mp[x][y+1];
    if(y-1>=1&&y-1<=m) res+=mp[x][y-1];
    return res+mp[x][y];
}
int main(){
    scanf("%d %d", &n, &m);
    for(int i=0;i<=n;++i)
    for(int j=0;j<=m;++j)
        f[i][j][0]=f[i][j][1]=0x3f3f3f3f;
    for(int i=1;i<=n;++i)
    for(int j=1;j<=m;++j)
        scanf("%d", &mp[i][j]);
    f[1][1][0]=f[1][1][1]=calc(1, 1);
    for(int i=1;i<=n;++i)
    for(int j=1;j<=m;++j){
        //f[i][j][0]当前状态从上面转移而来
        f[i][j][0]=min(f[i-1][j][1]+mp[i][j+1]+mp[i+1][j], f[i][j][0]);
        f[i][j][0]=min(f[i-1][j][0]+mp[i+1][j]+mp[i][j-1]+mp[i][j+1], f[i][j][0]);
        //f[i][j][0]当前状态从左面转移而来
        f[i][j][1]=min(f[i][j-1][1]+mp[i][j+1]+mp[i-1][j]+mp[i+1][j], f[i][j][1]);
        f[i][j][1]=min(f[i][j-1][0]+mp[i][j+1]+mp[i+1][j], f[i][j][1]);
    }
    printf("%d", min(f[n][m][0], f[n][m][1]));
    return 0;
}

This is a simulation game on campus to do a question, at first thought it was a road sign DP questions lead to ideas are wrong, Jing Xiaxin slowly behind the decision analysis came up with positive solutions, visible push sample importance. Also be sure not to underestimate the enemy.

Guess you like

Origin www.cnblogs.com/santiego/p/11563826.html
DP