#include #include long long a[1010][1010],b[1010][1010],f[1010][1010]; int main() { long long n,m,i,j,c,ans,x,y,k; while (scanf("%I64d",&n)!=EOF) { scanf("%I64d",&m); for (i=1;i<=n;i++) for (j=1;j<=m;j++) scanf("%I64d",&a[i][j]); for (i=0;i<=n;i++) for (j=0;j<=m;j++) f[i][j]=0; for (i=1;i<=n;i++) for (j=1;j<=m;j++) { if ((i+j)%2==1) { x=100000000; y=100000000; k=10000000; if (i>2) x=f[i-2][j]+a[i-1][j]*a[i][j]; if (j>2) y=f[i][j-2]+a[i][j-1]*a[i][j]; if (x>y) x=y; y=10000000; if (i>1 && j>1) { k=a[i][j]*a[i-1][j]; if (j>1) y=a[i][j]*a[i][j-1]; if (k>y) k=y; y=k+f[i-1][j-1]; if (x>y) x=y; } f[i][j]=x; f[1][2]=a[1][1]*a[1][2]; f[2][1]=a[1][1]*a[2][1]; } } printf("%I64d\n",f[n][m]); } }