HDU 2612 Find a way

HDU 2612 Find a way

题目大意:
y和m要去肯德基聚餐,图中有多个kfc,他们要选的那个kfc必须到彼此的所用时间之和最小,问最少需要多少时间。

题目思路:
将Y和M分开进行BFS,
然后根据二者到达KFC的时间总和,取用时最少的kfc
推荐与这题类似并且稍微复杂的题:UVA 11624

具体代码:

#include<iostream>
#include<queue>
#include<cstdio>
#include<string>

using namespace std;

int step[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int roads[205][205];
int cost_by_Y[205][205]; //表示Y到该处的时间
int cost_by_M[205][205];	//表示M到该处的时间
int visit[205][205];	
const int INF = 1e5;
int ans = INF;
int r, c;

void cmp_time()
{
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
		{
			if ( roads[i][j]==2) {
				if (cost_by_Y[i][j] + cost_by_M[i][j]<ans)	
				{
					ans = cost_by_Y[i][j] + cost_by_M[i][j];
				}
			}
		}
}
void bfs(int x, int y, int cost[][205])
{
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
			 cost[i][j]=INF,visit[i][j] = 0;//初始化
	queue<pair<int, int>> q;
	q.push(pair<int, int>(x, y));
	visit[x][y] = 1;
	cost[x][y] = 0;
	
	while (!q.empty())
	{
		pair<int, int> t = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int x = t.first, y = t.second;
			x += step[i][0], y += step[i][1];
			if (x >= 0 && x < r &&y >= 0 && y < c && !visit[x][y] && roads[x][y]) {
				visit[x][y] = 1;
				cost[x][y] = cost[t.first][t.second] + 1;
				q.push(pair<int, int>(x, y));
			}
		}
	}

}
int main()
{
	while (cin >> r >> c)
	{
		int x1, y1, x2, y2;
		for (int i = 0; i < r; i++)
		{
			string s;
			cin >> s;
			for (int j = 0; j < c; j++)
			{
				if (s[j] == '#')roads[i][j] = 0;
				else if (s[j] == '.')roads[i][j] = 1;
				else if (s[j] == '@')roads[i][j] = 2;
				else if (s[j] == 'Y') {
					roads[i][j] = 1;
					x1 = i, y1 = j;
				}
				else if(s[j]=='M'){
					roads[i][j] = 1;
					x2 = i, y2 = j;	
				}
			}
		}
		bfs(x1, y1, cost_by_Y);
		bfs(x2, y2, cost_by_M);
		cmp_time();
		printf("%d\n", ans * 11);
		ans = INF;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值