Find a path

在矩阵中,找一条到从(1,1)到(n,m)(只能向上,右走)的路径,使路径上方差最小。

对于S=∑N1(ai−x¯)2<∑N1(ai−x)2(x≠x¯)
而本题x¯范围很小,暴力枚举即可

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
#include<cmath>
#include<cctype>
#include<ctime>
using namespace std;
#define For(i,n) for(int i=1;i<=n;i++)
#define Fork(i,k,n) for(int i=k;i<=n;i++)
#define Rep(i,n) for(int i=0;i<n;i++)
#define ForD(i,n) for(int i=n;i;i--)
#define RepD(i,n) for(int i=n;i>=0;i--)
#define Forp(x) for(int p=pre[x];p;p=next[p])
#define Forpiter(x) for(int &p=iter[x];p;p=next[p])
#define Lson (x<<1)
#define Rson ((x<<1)+1)
#define MEM(a) memset(a,0,sizeof(a));
#define MEMI(a) memset(a,127,sizeof(a));
#define MEMi(a) memset(a,128,sizeof(a));
#define INF (2139062143)
#define F (100000007)
#define MAXN (30+10)
#define eps 1e-4
typedef long long ll;
ll mul(ll a,ll b){return (a*b)%F;}
ll add(ll a,ll b){return (a+b)%F;}
ll sub(ll a,ll b){return (a-b+llabs(a-b)/F*F+F)%F;}
void upd(ll &a,ll b){a=(a%F+b%F)%F;}
int f[MAXN][MAXN];
int a[MAXN][MAXN],n,m;
int sqr(int x){return x*x;}
int calc(int x)
{
int N=n+m-1;
For(i,n) For(j,m)
{
if (i==1&&j==1) f[i][j]=sqr(N*a[1][1]-x);
else if (i==1) f[i][j]=f[i][j-1]+sqr(N*a[i][j]-x);
else if (j==1) f[i][j]=f[i-1][j]+sqr(N*a[i][j]-x);
else f[i][j]=min(f[i-1][j],f[i][j-1])+sqr(N*a[i][j]-x);

}
return f[n][m]/N;
}
int main()
{
// freopen("path.in","r",stdin);
// freopen(".out","w",stdout);

int T;cin>>T;
For(kcase,T) {

cin>>n>>m;
For(i,n) For(j,m) scanf("%d",&a[i][j]);

int l=0,r=2000;

int ans=INF;
Fork(i,l,r) {

ans=min(ans,calc(i));

}


printf("Case #%d: %d\n",kcase,ans);
}



return 0;
}