HDU 2612 Find a Way

这道题的英语水平非常的惨不忍睹(虽然作为同样精通Chinglish的中国人我完全可以看懂,但还是莫名地觉得搞xiao啊233

对两个人分别bfs一下,记录每个kfc所需的总时间,最后输出最小的即可,几点注意

1. 要求输出的答案是总步数*11,因为走一步要十一分钟

2.因为有可能某些kfc两个人都到达不了,所以可能会出现某些kfc用时为0,最后比较出最小值时选择非零值即可

3.两人的起始位置能不能被另一人通过貌似对结果无影响,两种写法都AC了,不过我个人倾向于可以走的理解

这题我用了STL的map和queue,可能因此速度较慢(31ms),是很多dalao用时的两倍多

#include<iostream>
#include<queue>
#include<map>
using namespace std;
struct loc
{
	int r, c, th;
};
queue<loc> q;
map<pair<int, int>, int> ktime; //记录某位置(r,c)处的kfc的总用时
const int dir[][2] = { { 0,1 },{ 0,-1 },{ 1,0 },{ -1,0 } };
int n, m, ans;
bool vis[200][200];
char g[200][201];
void bfs(int r, int c)
{
	for (int i = 0; i < n; i++) memset(vis[i], 0, sizeof(bool)*m);
	size_t cnt = 0;
	int nx, ny;
	while (!q.empty()) q.pop();
	q.push({ r,c,0 });
	while (!q.empty() && cnt<ktime.size())
	{
		loc t = q.front(); q.pop();
		for (int i = 0; i<4; i++)
		{
			nx = t.r + dir[i][0];
			ny = t.c + dir[i][1];
			if (nx >= 0 && nx < n&&ny >= 0 && ny < m&&g[nx][ny]!='#' && !vis[nx][ny])
			{
				vis[nx][ny] = true;
				q.push({ nx,ny,t.th + 1 });
				if (g[nx][ny] == '@')
				{
					cnt++;
					ktime[{nx, ny}] += t.th + 1;
				}
			}
		}
	}
}
int main()
{
	int ry, cy, rm, cm;
	while (cin >> n >> m)
	{
		ans = 10000000;
		ktime.clear();
		for (int i = 0; i<n; i++)
		{
			cin >> g[i];
			for (int j = 0; j<m; j++)
				if (g[i][j] == '@') ktime.insert({ { i,j },0 });
				else if (g[i][j] == 'Y') ry = i, cy = j;
				else if (g[i][j] == 'M') rm = i, cm = j;
		}
		bfs(ry, cy);
		bfs(rm, cm);
                //auto关键字太好用了哈哈哈,不用每次迭代器都写一长串了
		for (auto it = ktime.begin(); it != ktime.end(); it++)
			if (it->second&&it->second<ans) ans = it->second;
		cout << ans * 11 << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Accsc/article/details/81609951