HDU - 5492 Find a path(dp)

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)∑i=1N+M−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.

参考题解
emmm,文章里面讲的很明白了,写的很好。我们dp维护两个比较关键的值,一个是经过的路径的权值和,另一个是权值平方的加和,权值平方的加和太大了,必然不如用权值和作为第三维更好。数组中存的为平方和。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int n, m;
int mp[35][35], dp[35][35][1805];

int main()
{
    int T;
    scanf("%d", &T);
    for(int cas = 1; cas <= T; cas++)
    {
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                scanf("%d", &mp[i][j]);
        memset(dp, INF, sizeof(dp));
        dp[1][1][mp[1][1]] = mp[1][1]*mp[1][1];
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
            {
                if(i+1 <= n)
                    for(int k = 0; k <= 1800; k++)
                        if(dp[i][j][k] != INF)
                            dp[i+1][j][k+mp[i+1][j]] = min(dp[i][j][k]+mp[i+1][j]*mp[i+1][j], dp[i+1][j][k+mp[i+1][j]]);
                if(j+1 <= m)
                    for(int k = 0; k <= 1800; k++)
                        if(dp[i][j][k] != INF)
                            dp[i][j+1][k+mp[i][j+1]] = min(dp[i][j][k]+mp[i][j+1]*mp[i][j+1], dp[i][j+1][k+mp[i][j+1]]);
            }
        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);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/100689465