hdu 5433(bfs+dp)

30 篇文章 0 订阅

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

解题思路:

dp[i][j][k]表示在(x,y)点,毅力为k时的最小体力。由于每个点可能会走多次,所以用bfs往四个方向搜索,不过考虑到最优情况,只有比dp[i][j][k]更小,才把它放进队列里。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;

const int maxn = 55;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
struct Node
{
	int x,y,t; //t表示意志
	double power; //体力

	Node(){}
	Node(int _x,int _y,int _t,double _power)
	{
		x = _x, y = _y, t = _t;
		power = _power;
	}
};
int n,m,k,map[maxn][maxn];
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int sx,sy,ex,ey;
double dp[maxn][maxn][maxn];

void bfs()
{
	queue<Node> q;
	dp[sx][sy][k] = 0;
	q.push(Node(sx,sy,k,dp[sx][sy][k]));
	while(!q.empty())
	{
		Node cur = q.front();
		q.pop();
		for(int i = 0; i < 4; i++)
		{
			int newx = cur.x + dir[i][0];
			int newy = cur.y + dir[i][1];
			if(newx < 1 || newx > n || newy < 1 || newy > m || map[newx][newy] == -1) continue;
			Node next;
			next.x = newx,next.y = newy;
			next.t = cur.t - 1;
			double tmp = abs(map[next.x][next.y] - map[cur.x][cur.y]) / (cur.t * 1.0);
			if(next.t > 0 && dp[next.x][next.y][next.t] > dp[cur.x][cur.y][cur.t] + tmp)
			{
				dp[next.x][next.y][next.t] = dp[cur.x][cur.y][cur.t] + tmp;
				next.power = dp[next.x][next.y][next.t];
				q.push(next);
			}
		}
	}
}

int main()
{
	int t;
	char str[maxn];
	cin >> t;
	while(t--)
	{
		cin >> n >> m >> k;
		for(int i = 1; i <= n; i++)
		{
			cin >> str + 1;
			for(int j = 1; j <= m; j++)
			{
				if(str[j] == '#') map[i][j] = -1;
				else map[i][j] = str[j] - '0';
			}
		}
		cin >> sx >> sy >> ex >> ey;
		if(k <= 0)  
        {  
            printf("No Answer\n");  
            continue;  
        }  
		for(int i = 0; i <= n; i++)
			for(int j = 0; j <= m; j++)
				for(int r = 0; r <= k; r++)
					dp[i][j][r] = inf;
		bfs();
		double MIN = dp[ex][ey][1];
		for(int i = 1; i <= k; i++)
			MIN = min(MIN,dp[ex][ey][i]);
		if(abs(MIN - inf) > eps)
			printf("%.2lf\n",MIN);
		else printf("No Answer\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值