Frog fell into a maze. This maze is a rectangle containing NN rows and MM columns. Each grid in this maze contains a number, which is called the magic value. Frog now stays at grid (1, 1), and he wants to go to grid (N, M). For each step, he can go to either the grid right to his current location or the grid below his location. Formally, he can move from grid (x, y) to (x + 1, y) or (x, y +1), if the grid he wants to go exists.
Frog is a perfectionist, so he’d like to find the most beautiful path. He defines the beauty of a path in the following way. Let’s denote the magic values along a path from (1, 1) to (n, m) as A1,A2,…AN+M−1A1,A2,…AN+M−1, and AavgAavg is the average value of all AiAi. The beauty of the path is (N+M–1)(N+M–1) multiplies the variance of the values:(N+M−1)∑N+M−1i=1(Ai−Aavg)2(N+M−1)∑i=1N+M−1(Ai−Aavg)2
In Frog’s opinion, the smaller, the better. A path with smaller beauty value is more beautiful. He asks you to help him find the most beautiful path.
Input
The first line of input contains a number TT indicating the number of test cases (T≤50T≤50).
Each test case starts with a line containing two integers NN and MM (1≤N,M≤301≤N,M≤30). Each of the next NN lines contains MM non-negative integers, indicating the magic values. The magic values are no greater than 30.
Output
For each test case, output a single line consisting of “Case #X: Y”. XX is the test case number starting from 1. YY is the minimum beauty value.
Sample Input
1
2 2
1 2
3 4
Sample Output
Case #1: 14
给出的那个式子首先要化简。化简之后就是(n+m-1)*∑(ai^2)-∑(ai) ^2.(自己画画,写的不明白)
数据量很小,而且每个位置的数字最多就是30。那么经过的路径上最大就是1770。我们可以每个位置枚举这个数字,dp[i][j][k]代表着到达(i,j)时经过数据和为k的最小花费。
状态转移方程为:
dp[i+1][j][k+a[i+1][j]]=min(dp[i+1][j][k+a[i+1][j]],dp[i][j][k]+a[i+1][j]*a[i+1][j]);
dp[i][j+1][k+a[i][j+1]]=min(dp[i][j+1][k+a[i][j+1]],dp[i][j][k]+a[i][j+1]*a[i][j+1]);
代码如下:
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxx=31;
int a[maxx][maxx];
int dp[maxx][maxx][1810];
int n,m;
int main()
{
int t;
scanf("%d",&t);
int tt=0;
while(t--)
{
scanf("%d%d",&n,&m);
memset(dp,inf,sizeof(dp));//一开始的初始化
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++) scanf("%d",&a[i][j]);
}
dp[1][1][a[1][1]]=a[1][1]*a[1][1];//a[1][1]位置设置为a[1][1]*a[1][1]。
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(i+1<=n)
{
for(int k=0;k<=1770;k++)
{
if(dp[i][j][k]!=inf)
{
dp[i+1][j][k+a[i+1][j]]=min(dp[i+1][j][k+a[i+1][j]],dp[i][j][k]+a[i+1][j]*a[i+1][j]);
}
}
}
if(j+1<=m)
{
for(int k=0;k<=1770;k++)
{
if(dp[i][j][k]!=inf)
{
dp[i][j+1][k+a[i][j+1]]=min(dp[i][j+1][k+a[i][j+1]],dp[i][j][k]+a[i][j+1]*a[i][j+1]);
}
}
}
}
}
int ans=inf;
for(int i=0;i<=1800;i++)
{
if(dp[n][m][i]!=inf)
ans=min(ans,(n+m-1)*dp[n][m][i]-i*i);//枚举最终路径上的值,不断更新最终答案
}
printf("Case #%d: %d\n",++tt,ans);
}
}
努力加油a啊,(o)/~