码迷,mamicode.com
首页 > 其他好文 > 详细

HDU-5492 Find a path (枚举+DP)

时间:2015-09-28 13:09:02      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

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+M1, and Aavg is the average value of all Ai. The beauty of the path is (N+M1) multiplies the variance of the values:(N+M1)N+M1i=1(AiAavg)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 (T50).
Each test case starts with a line containing two integers N and M (1N,M30). 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
 
 
题目大意:在一个数字方格中,寻找一条从左上角到右下角的路径,使得路径上的数字方差最小。
题目分析:这是2015年合肥网络赛的一道比较简单的题目,赛时没有做出来,惭愧!这道题的一种解法是这样的,枚举路径上的数字和,使其变成数塔问题,递推求解。
 
代码如下:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

double dp[35][35];
int mp[35][35],n,m;

double DP(int eva)
{
    double k=n+m-1.0;
    dp[n-1][m-1]=(mp[n-1][m-1]-eva/k)*(mp[n-1][m-1]-eva/k);
    for(int i=n-2;i>=0;--i)
        dp[i][m-1]=(mp[i][m-1]-eva/k)*(mp[i][m-1]-eva/k)+dp[i+1][m-1];
    for(int i=m-2;i>=0;--i)
        dp[n-1][i]=(mp[n-1][i]-eva/k)*(mp[n-1][i]-eva/k)+dp[n-1][i+1];
    for(int i=n-2;i>=0;--i)
        for(int j=m-2;j>=0;--j)
            dp[i][j]=(mp[i][j]-eva/k)*(mp[i][j]-eva/k)+min(dp[i+1][j],dp[i][j+1]);
    return (n+m-1)*dp[0][0];
}

int main()
{
    int T,cas=0;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<n;++i)
            for(int j=0;j<m;++j)
                scanf("%d",&mp[i][j]);

        double ans=1e10;
        for(int i=0;i<=1770;++i)
            ans=min(ans,DP(i));
        printf("Case #%d: %.0lf\n",++cas,ans);
    }
    return 0;
}

  

HDU-5492 Find a path (枚举+DP)

标签:

原文地址:http://www.cnblogs.com/20143605--pcx/p/4843683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!