HDU 5492 Find a path(DP)

来源:互联网 发布:自学游戏编程 编辑:程序博客网 时间:2024/05/16 02:07

思路:将式子化开其实就是求(n+m-1)*s1-s2的最小值,s1表示各个格子的平方和,s2表示和的平方,留意到数据范围较小,令dp[i][j][k]为走到第i行第j列当前和为k的平方和的最小值,最后答案就是(n+m-1)*dp[i][j][k]-k*k


#include<bits/stdc++.h>using namespace std;#define inf 1e9int a[33][33];int dp[33][33][1807];int main(){    int T,cas=1;scanf("%d",&T);while(T--){int n,m;scanf("%d%d",&n,&m);for(int i = 1;i<=n;i++)for(int j = 1;j<=m;j++)scanf("%d",&a[i][j]);for(int i = 1;i<=n;i++)for(int j = 1;j<=m;j++)for(int k = 0;k<=1800;k++)  dp[i][j][k]=inf;for(int i = 1;i<=n;i++)for(int j = 1;j<=m;j++){for(int k = 0;k<=1800;k++){                    if(i==1 && j==1 && a[i][j]==k)dp[i][j][k]=a[i][j]*a[i][j];if(k>=a[i][j]){                        if(i>1)dp[i][j][k]=min(dp[i][j][k],dp[i-1][j][k-a[i][j]]+a[i][j]*a[i][j]);if(j>1)dp[i][j][k]=min(dp[i][j][k],dp[i][j-1][k-a[i][j]]+a[i][j]*a[i][j]);}}}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",cas++,ans);}}


Description

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+M1, and Aavg is the average value of all Ai. The beauty of the path is (N+M1) multiplies the variance of the values: 
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  indicating the number of test cases (). 
Each test case starts with a line containing two integers  and  (). Each of the next  lines contains  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”.  is the test case number starting from 1.  is the minimum beauty value.

Sample Input

12 21 23 4

Sample Output

Case #1: 14


0 0
原创粉丝点击