#include #include #include #include #include using namespace std; const int N = 1050; int dp[N][N]; int map[N][N]; int n,m; int getint() { int res=0; char ch=getchar(); while((ch<'0' || ch>'9') && ch!='-') ch=getchar(); bool fan=0; if(ch=='-') { fan=1; ch=getchar(); } while('0'<=ch && ch<='9') { res=res*10+ch-'0'; ch=getchar(); } if(fan) res=-res; return res; } void f() { int i,j,k; m=getint(); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) map[i][j]=getint(); } memset(dp,0x3f,sizeof dp); dp[1][2]=map[1][1]*map[1][2]; dp[2][1]=map[1][1]*map[2][1]; for(k=5;k<=n+m;k+=2) { for(i=1;in || j<1 || j>m) continue; if(i>2) dp[i][j]=min(dp[i][j],dp[i-2][j]+map[i-1][j]*map[i][j]); if(j>2) dp[i][j]=min(dp[i][j],dp[i][j-2]+map[i][j-1]*map[i][j]); if(i>1 && j>1) dp[i][j]=min(dp[i][j],dp[i-1][j-1]+min(map[i][j-1],map[i-1][j])*map[i][j]); } } printf("%d\n",dp[n][m]); } int main() { while(scanf("%d",&n)!=EOF) f(); return 0; }