题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5433
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1346 Accepted Submission(s): 384
Problem Description
Due to the curse made by the devil,Xiao Ming is stranded on a mountain and can hardly escape.
This mountain is pretty strange that its underside is a rectangle which size is 1 point of will.
Because of the devil's strong,Ming has to find a way cost least physical power to defeat the devil.
Can you help Xiao Ming to calculate the least physical power he need to consume.
This mountain is pretty strange that its underside is a rectangle which size is 1 point of will.
Because of the devil's strong,Ming has to find a way cost least physical power to defeat the devil.
Can you help Xiao Ming to calculate the least physical power he need to consume.
Input
The first line of the input is a single integer ),coordinates is not a barrier.
Output
For each testcase print a line ,if Xiao Ming can beat devil print the least physical power he need to consume,or output "
(The result should be rounded to 2 decimal places)
(The result should be rounded to 2 decimal places)
Sample Input
3
4 4 5
2134
2#23
2#22
2221
1 1
3 3
4 4 7
2134
2#23
2#22
2221
1 1
3 3
4 4 50
2#34
2#23
2#22
2#21
1 1
3 3
Sample Output
1.03
0.00
No Answer
题解:
看网上都是bfs的解法,这里来一发动态规划。
设dp[i][j][k]代表小明走到(i,j)时还剩k个单位的fighting will的状态;
令(i',j') 表示(i,j)上下左右的某一点,那么易得转移方程:
dp[i][j][k]=min(dp[i][j][k],dp[i'][j'][k+1]+abs(H[i][j]-H[i'][j'])/(k+1))
由于状态转移的顺序比较复杂,所有可以用记忆化搜索的方式来求解。
最终ans=min(dp[x2][y2][1],......,dp[x2][y2][k]]).
代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn=55; 9 10 double dp[maxn][maxn][maxn]; 11 bool vis[maxn][maxn][maxn]; 12 char mat[maxn][maxn]; 13 14 int n,m,len; 15 int X1,Y1,X2,Y2; 16 17 void init(){ 18 memset(vis,0,sizeof(vis)); 19 memset(dp,0x7f,sizeof(dp)); 20 } 21 22 const int dx[]={-1,1,0,0}; 23 const int dy[]={0,0,-1,1}; 24 double solve(int x,int y,int k){ 25 if(vis[x][y][k]) return dp[x][y][k]; 26 vis[x][y][k]=1; 27 for(int i=0;i<4;i++){ 28 int tx=x+dx[i],ty=y+dy[i]; 29 if(tx<1||tx>n||ty<1||ty>m||k+1>len||mat[tx][ty]=='#') continue; 30 double add=fabs((mat[x][y]-mat[tx][ty])*1.0)/(k+1); 31 dp[x][y][k]=min(dp[x][y][k],solve(tx,ty,k+1)+add); 32 } 33 return dp[x][y][k]; 34 } 35 36 int main(){ 37 int tc; 38 scanf("%d",&tc); 39 while(tc--){ 40 init(); 41 scanf("%d%d%d",&n,&m,&len); 42 for(int i=1;i<=n;i++) scanf("%s",mat[i]+1); 43 scanf("%d%d%d%d",&X1,&Y1,&X2,&Y2); 44 dp[X1][Y1][len]=0; vis[X1][Y1][len]=1; 45 double ans=0x3f; 46 int flag=0; 47 for(int k=len;k>=1;k--){ 48 double tmp=solve(X2,Y2,k); 49 if(ans>tmp){ 50 flag=1; 51 ans=tmp; 52 } 53 } 54 if(flag) printf("%.2lf\n",ans); 55 else printf("No Answer\n"); 56 } 57 return 0; 58 }