• CF1063B Labyrinth


    大家一起膜Rorshach。

    一般的$bfs$会造成有一些点访问不到的情况,在$system test$的时候会$WA40$(比如我……)。

    发现这张地图其实是一个边权只有$0/1$的图,我们需要计算的是从$(r, c)$开始到每一个点的最短路,因为边权只有两种的特性,我们可以用一个双端队列,每一次向上向下走的放在队首,每一次向左向右走放在队尾,就可以得到正确的解。

    也可以用优先队列,这样子多一个$log$。

    时间复杂度$O(n^2)$。

    Code:

    #include <cstdio>
    #include <cstring>
    #include <deque>
    #include <iostream>
    using namespace std;
    
    const int N = 2005;
    const int dx[] = {0, 1, 0, -1};
    const int dy[] = {1, 0, -1, 0};
    
    int n, m, r, c, lstp, rstp, ans = 0;
    bool vis[N][N];
    char mp[N][N];
    
    struct Node {
        int x, y, ls, rs;
    
        inline Node(int nowX = 0, int nowY = 0, int nowLs = 0, int nowRs = 0) {
            x = nowX, y = nowY, ls = nowLs, rs = nowRs;
        }
    
    };
    deque <Node> Q;
    
    inline bool valid(Node now) {
        return now.x >= 1 && now.x <= n && now.y >= 1 && now.y <= m && mp[now.x][now.y] != '*' && !vis[now.x][now.y];
    }
    
    void bfs() {
        Q.push_front(Node(r, c, lstp, rstp));
        vis[r][c] = 1, ++ans;
        for(; !Q.empty(); ) {
            Node out = Q.front(); Q.pop_front();
            for(int i = 0; i < 4; i++) {
                Node in = Node(out.x + dx[i], out.y + dy[i], out.ls - (dy[i] == -1), out.rs - (dy[i] == 1));
                if(!valid(in)) continue;
                if(in.ls == -1 || in.rs == -1) continue;
                if(i == 0 || i == 2) Q.push_back(in);
                else Q.push_front(in);
                vis[in.x][in.y] = 1, ++ans;
            }
        }
    }
    
    int main() {
        scanf("%d%d%d%d%d%d", &n, &m, &r, &c, &lstp, &rstp);
        for(int i = 1; i <= n; i++) scanf("%s", mp[i] + 1);
    
        bfs();
    
    /*    for(int i = 1; i <= n; i++, printf("
    "))
            for(int j = 1; j <= m; j++)
                printf("%d ", vis[i][j]);    */
    
        printf("%d
    ", ans);
        return 0;
    }
    View Code
  • 相关阅读:
    json基础
    css语法以及css选择器
    HTML语义化标签
    CSS插入的四种方式
    Hibernate主键生成策略及选择
    HIbernate处理数据更新丢失
    数据库的四大特性以及事务的隔离级别
    MD5加密
    redis主从复制
    redis的持久化方案
  • 原文地址:https://www.cnblogs.com/CzxingcHen/p/9790480.html
Copyright © 2020-2023  润新知