NOWCODER – CSL的校园卡(多进程bfs)

https://ac.nowcoder.com/acm/contest/190/H
就是在节点里保存两个人的坐标,然后两个点同时向周围扩展。vis保存了所有情况的状态,暂时不知道有啥用,可能是个回溯的作用?

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const int maxn = 2e6 + 5, inf = 0x3f3f3f3f;
char a[5][5];//注意多开个空间存0
int n, m, pa, pb, all;
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
bool vis[1 << 17][4][4][4][4];
struct node{
    int x1, y1, x2, y2, have, time;
};
int getpos(int x, int y){ return 1 << (x * m + y + 1);}
int bfs(int x, int y, int have, int t)
{
    queue<node> qe;
    qe.push(node{x, y, x, y, have, 0});
    while (!qe.empty()){
        node e = qe.front(); qe.pop();
        if (e.x1 < 0 || e.y1 < 0 || e.x1 >= n || e.y1 >= m) continue;
        if (e.x2 < 0 || e.y2 < 0 || e.x2 >= n || e.y2 >= m) continue;
        if (a[e.x1][e.y1] == 'X' || a[e.x2][e.y2] == 'X') continue;
        if (e.have == all) return e.time;//注意顺序,可能超范围了但是也相等,这时候时间就多1了。
        if (vis[e.have][e.x1][e.y1][e.x2][e.y2]) continue;
        vis[e.have][e.x1][e.y1][e.x2][e.y2] = 1;
        for (int i = 0; i < 4; ++i){
            for (int j = 0; j < 4; ++j){
                int temp = e.have | getpos(e.x1 + dx[i], e.y1 + dy[i]) | getpos(e.x2 + dx[j], e.y2 + dy[j]);
                qe.push(node{e.x1 + dx[i], e.y1 + dy[i], e.x2 + dx[j], e.y2 + dy[j], temp, e.time + 1});
            }
        }
    }
    return -1;
}
int main()
{
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; ++i) scanf("%s", a[i]);
    int sx, sy;
    for (int i = 0; i < n; ++i){
        for (int j = 0; j < m; ++j){
            if (a[i][j] == 'S') sx = i, sy = j;
            else if (a[i][j] == 'O') all |= getpos(i, j);
        }
    }
    all |= getpos(sx, sy);
    cout << bfs(sx, sy, getpos(sx, sy), 0) << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值