题目描述
Frog fell into a maze. This maze is a rectangle containing N rows and M 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−1, and Aavg is the average value of all Ai. The beauty of the path is (N+M–1) multiplies the variance of the values:(N+M−1)∑N+M−1i=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.
算法思路
- 咋一看这道题是很复杂的,因为一些数的平均值是会不断的变化的。但是,我们对这个求和公式进行一些化简,情况就会有所不同。
- 公式化简如下所示:
ans=k∗∑i=1k(Ai−Aavg)2
ans=k∗∑i=1k(A2i+2∗AiAavg+A2avg)
ans=k∗∑i=1kA2i−(∑i=1kAi)2
3.从化简后的公式中,我们可以看到,当这个路径中的和确定的时候,其路径中的数的平方和越小,这个路径的魅力值越小,由此我们可以使用背包算法进行解题。 - 同时,还可以通过滚动数组的技术来压缩这个解法的空间复杂度。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
#define MAXN 35
#define MAXF 2005
#define INF 0x3f3f3f3f
int grid[MAXN][MAXN];
int n,m;
int dp[MAXN][MAXN][MAXF];
int cas = 0,T;
void Solve()
{
int i,j,k;
int limit = (n+m-1)*30+5;
int ans=INF;
//Initialization
memset(dp,INF,sizeof(dp));
dp[0][0][grid[0][0]]=grid[0][0]*grid[0][0];
for(i=0;i<n;i++){
for(j=0;j<m;j++){
//to prevent segmentation fault
if(!i&&!j)continue;
for(k=grid[i][j];k<limit;k++){
if(i>0)dp[i][j][k] = min(dp[i][j][k],dp[i-1][j][k-grid[i][j]]+grid[i][j]*grid[i][j]);
if(j>0)dp[i][j][k] = min(dp[i][j][k],dp[i][j-1][k-grid[i][j]]+grid[i][j]*grid[i][j]);
}
}
}
//form the final answer
for(i=grid[n-1][m-1];i<limit;i++){
if(dp[n-1][m-1][i]==INF)continue;
ans = min(ans,(n+m-1)*dp[n-1][m-1][i]-i*i);
}
printf("Case #%d: %d\n",++cas,ans);
return;
}
int main()
{
//freopen("input","r",stdin);
int i,j;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(i=0;i<n;i++){
for(j=0;j<m;j++)
scanf("%d",&grid[i][j]);
}
Solve();
}
return 0;
}