HDU 5492(DP) Find a path

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5492

题目大意是有一个矩阵,从左上角走到右下角,每次能向右或者向下,把经过的数字记下来,找出一条路径是这些数的方差最小。

Find a path

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 961    Accepted Submission(s): 431

Problem 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+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.
 
Input
The first line of input contains a number T indicating the number of test cases (T≤50).
Each test case starts with a line containing two integers N and M (1≤N,M≤30). Each of the next N lines contains M 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”. X is the test case number starting from 1. Y is the minimum beauty value.
 
Sample Input
1
2 2
1 2
3 4
 
Sample Output
Case #1: 14
 #include <iostream>
#include <cstring>
#define inf 0x3f3f3f3f
using namespace std; int mi(int x,int y)
{
if (x<y)
return x;
else
return y;
}
int ans,t,n,m,dp[][][],a[][];
int main()
{ cin>>t;
for (int cas=;cas<=t;cas++)
{
cin>>n>>m;
for (int i=;i<=n;i++)
for (int j=;j<=m;j++)
cin>>a[i][j]; memset(dp,inf,sizeof(dp));
dp[][][]=;
dp[][][]=; for (int i=;i<=n;i++)
{
for (int j=;j<=m;j++)
{
for (int k=;k<=;k++)
{
if (dp[i-][j][k]!=inf)
{
dp[i][j][k+a[i][j]]=mi(dp[i][j][k+a[i][j]],dp[i-][j][k]+a[i][j]*a[i][j]);
}
if (dp[i][j-][k]!=inf)
{
dp[i][j][k+a[i][j]]=mi(dp[i][j][k+a[i][j]],dp[i][j-][k]+a[i][j]*a[i][j]);
}
}
}
}
ans=inf;
for (int i=;i<=;i++)
{
if (dp[n][m][i]!=inf)
ans=mi(ans,dp[n][m][i]*(n+m-)-i*i);
}
cout <<"Case #"<<cas<<": "<<ans<<endl;
}
return ;
}
 
上一篇:CF 435B Pasha Maximizes(贪心)


下一篇:PHP里用户密码的回复和管理