Hdu 2612 Find a way (bfs)

这篇博客讨论了一种算法问题,涉及到两个人在二维网格中寻找最近的交汇点(@)。原方法使用双向BFS遍历所有交汇点,但超时。改进后的策略是分别计算两个人到达每个交汇点的最短时间,并存储在time1和time2数组中,最后找到总时间的最小值。代码中展示了如何实现这个优化策略。
摘要由CSDN通过智能技术生成

  

题意:两个人需要在一个@处见面,图中可能有若干个@,求两个人所需时间和的最小值,一开始写的是两个起始点分别对每一个@进行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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值