首页 > 程序开发 > 软件开发 > 其他 >

HDU 5492 Find a path(DP)

2016-09-16

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

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

#include
using namespace std;
#define inf 1e9
int 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 containingNrows andMcolumns. 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&#39;d like to find the most beautiful path. He defines the beauty of a path in the following way. Let&rsquo;s denote the magic values along a path from (1, 1) to (n, m) asA1,A2,…AN+M?1, andAavgis the average value of allAi. The beauty of the path is(N+M&ndash;1)multiplies the variance of the values:\\\\\\\\\\\\\\\\\\\\\\\\\\
In Frog&#39;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

1
2 2
1 2
3 4

Sample Output

Case #1: 14
相关文章
最新文章
热点推荐