1. 程式人生 > >hdu-5492-dp

hdu-5492-dp

ret rec alt sta icp under more include memset

Find a path

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


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+M1) 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 (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

Source 2015 ACM/ICPC Asia Regional Hefei Online 求方格迷宮裏的最小方差路徑。 化簡式子:

技術分享圖片

可以看出問題就是要使得所有的(N+M-1)*(A平方的和)減去所有A的和的平方達到最小。

令f[i][j][k]表示走到(i,j)處,且當前走過的格子的法力值的和為k(即SUM{A}=k)的時候的最小的SUM{Ai^2}的值。

最後答案就是MIN{ f[i][j][k]*(N+M-1)-k*k }

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define inf 0x3f3f3f3f
 4 int f[35][35][2000]; 
 5 int e[35][35];
 6 int main(){
 7     int N,M,T,i,j,k;
 8     cin>>T;
 9     for(int cas=1;cas<=T;++cas){
10         cin>>N>>M;
11         for(i=1;i<=N;++i){
12             for(j=1;j<=M;++j){
13                 cin>>e[i][j];
14             }
15         }
16     memset(f,inf,sizeof(f));
17     f[1][1][e[1][1]]=e[1][1]*e[1][1];
18     for(i=1;i<=N;++i){
19         for(j=1;j<=M;++j){
20             for(k=0;k<2000;++k){
21                 if(f[i][j][k]!=inf){
22                     f[i][j+1][k+e[i][j+1]]=min(f[i][j+1][k+e[i][j+1]],f[i][j][k]+e[i][j+1]*e[i][j+1]);
23                     f[i+1][j][k+e[i+1][j]]=min(f[i+1][j][k+e[i+1][j]],f[i][j][k]+e[i+1][j]*e[i+1][j]);
24                 }
25             }
26         }
27     }
28     int ans=inf;
29     for(i=0;i<2000;++i){
30         if(f[N][M][i]!=inf){
31             ans=min(ans,f[N][M][i]*(N+M-1)-i*i);
32         }
33     }
34     cout<<"Case #"<<cas<<": "<<ans<<endl;    
35     }
36     return 0;
37 }

hdu-5492-dp