最后公式化简后是 (n-m+1)Ai^2-路径和的平方
dp[i][j][k] 表示在i,j格子路径和为k的(n-m+1)Ai^2的最小值
最后答案是 dp[n][m][i]的最小值-路径和的平方
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;
#define rd(x) scanf("%d",&x)
#define rdd(x,y) scanf("%d%d",&x,&y)
#define rddd(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define rdddd(x,y,z,w) scanf("%d%d%d%d",&x,&y,&z,&w)
#define rds(s) scanf("%s",s)
#define rep(i,n) for(int i=0;i<n;i++)
#define LL long long
const int N = 2e5+10;
const int M=2000;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
int MOD=1e9+7;
int cas=1;
int n,m,k,q;
int dp[35][35][M];
int a[35][35];
int main()
{
#ifndef ONLINE_JUDGE
freopen("aaa","r",stdin);
#endif
int T;
rd(T);
while(T--){
rdd(n,m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) rd(a[i][j]);
memset(dp,0x3f,sizeof dp);
dp[0][1][0]=0;
dp[1][0][0]=0;
int step=n+m-1;
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){
for(int k=a[i][j];k<M;k++){
int u=k-a[i][j];
if(dp[i-1][j][u]!=inf) dp[i][j][k]=min(dp[i][j][k],dp[i-1][j][u]+step*a[i][j]*a[i][j]);
if(dp[i][j-1][u]!=inf) dp[i][j][k]=min(dp[i][j][k],dp[i][j-1][u]+step*a[i][j]*a[i][j]);
}
}
int ans=inf;
for(int i=0;i<M;i++){
ans=min(ans,dp[n][m][i]-(i*i));
}
printf("Case #%d: %d\n",cas++,ans);
}
return 0;
}