题意:两个人需要在一个@处见面,图中可能有若干个@,求两个人所需时间和的最小值,一开始写的是两个起始点分别对每一个@进行bfs,得到最短时间,很遗憾这样T掉了。想了一下,可以用两个time数组分别记录两个人到达每一个@的最短时间,这样只需要两次bfs,最后逐个比较一下,得到最小值就可以,写题还是要灵活,不能无脑写,多想一些可以降低时间复杂度的方法。
code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#define IO \
ios::sync_with_stdio(false); \
// cin.tie(0); \
// cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 2e2 + 5;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 998244353;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0};
struct Node
{
int x, y, step;
};
int mp[maxn][maxn];
char a[maxn][maxn];
bool vis[maxn][maxn];
int time1[maxn * maxn]; // 1 到达每个kfc的最短时间
int time2[maxn * maxn]; // 2 到达每个kfc的最短时间
int n, m, sx1, sy1, sx2, sy2;
int cnt = 0; // 记录kfc 数量
void BFS(int x, int y, int k)
{
memset(vis, 0, sizeof vis);
vis[x][y] = 1;
queue<Node> q;
q.push({x, y, 0});
while (!q.empty())
{
Node now = q.front();
q.pop();
if (a[now.x][now.y] == '@')
{
int id = mp[now.x][now.y];
if (k == 1)
time1[id] = now.step;
else
time2[id] = now.step;
}
for (int i = 0; i < 4; i++)
{
int tx = now.x + dis[i][0];
int ty = now.y + dis[i][1];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && !vis[tx][ty] && (a[tx][ty] == '.' || a[tx][ty] == '@'))
{
vis[tx][ty] = 1;
q.push({tx, ty, now.step + 1});
}
}
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
while (scanf("%d %d", &n, &m) == 2)
{
cnt = 0;
int ans = inf;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf(" %c", &a[i][j]);
if (a[i][j] == 'M')
sx1 = i, sy1 = j;
if (a[i][j] == 'Y')
sx2 = i, sy2 = j;
if (a[i][j] == '@')
mp[i][j] = cnt++;
}
BFS(sx1, sy1, 1);
BFS(sx2, sy2, 2);
for (int i = 0; i < cnt; i++)
{
ans = min(ans, time1[i] * 11 + time2[i] * 11);
}
printf("%d\n", ans);
}
return 0;
}