跳到正文

题解

P14469 [COCI 2025/2026 #1] 皇后 / Kraljica

__Charlie_Chen__约 4 分钟
原文

这是 2025年11月15日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月8日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 4 分钟
获赞
3
题目
P14469

版本

  1. v2当前
  2. v1

P14469 [COCI 2025/2026 #1] 皇后 / Kraljica

用户彻底怒了,bfs 爆搜全机房怒调两个多小时,最终极限卡常荣获最劣解。

思路

看了其它的代码,跑的都飞快,但是似乎不是很好想,这里提供一个非常好想的实现方法。

第一眼,这不是裸的 bfs 题吗,一个方向数组在 bfs 的时候向几个方向无限延申即可,如果遇到了一个点在地图外,那么再延伸下去会仍然在地图外,此时直接 break 即可。

于是你写出了这份代码:

code:

C++
int bfs(node sta, node end) {
    queue<node> q;
    vis[sta.x][sta.y] = 1;
    q.push(sta);
    while (!q.empty()) {
        node cur = q.front();
        q.pop();
        if(cur.x == end.x && cur.y == end.y) 
            return cur.ste;
        for(int i = 0; i < 8; ++i){
            int j = 0;
            while(1){
                ++j;
                int xx = cur.x + j * dx[i], yy = cur.y + j * dy[i];
                if (!check(xx, yy)) break;
                if (vis[xx][yy]) continue;
                if (s[xx][yy] == '#') break;
                vis[xx][yy] = 1;
                if (s[xx][yy] >= '1' && s[xx][yy] <= '9') {
                    char pid = s[xx][yy];
                    for (const auto& pp : p[pid - '0'])
                        if (pp.fi != xx || pp.se != yy){
                            if(vis[pp.fi][pp.se]) continue;
                            q.push(node(pp.fi, pp.se, cur.ste + 1));
                            vis[pp.fi][pp.se] = 1;
                        }
                    }
                q.push(node(xx, yy, cur.ste + 1));
            }
        }
    }
    return -1;
}

然后发现 TLE on #56 #111 #112 上了,为什么呢?构造一下极限数据:

代码
E#...
##...
.....
.....
....S

中间省略很多 .,此时,你发现起点和终点间的所有的点都会向八个方向延申,时间复杂度被卡成了 O(n3)O(n^3) 了,怎么办呢?直接说出解决方法吧。

将上面的代码中第 15、16 行交换一下即可,因为这样会少 check 很多次,卡常大法万岁!

最终我们以 #56 4.78s 的成绩极限过掉这个题。

main 函数如下:

C++
struct node{
    int x, y, ste;
    node(int x, int y, int ste) : x(x), y(y), ste(ste) {}
};
int main() {
    cin >> n >> m;
    node sta(-1, -1, 0), end(-1, -1, 0);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
        	cin >> s[i][j];
            if (s[i][j] == 'S')
                sta = node(i, j, 0);
            else if (s[i][j] == 'E')
                end = node(i, j, 0);
            else if (s[i][j] >= '1' && s[i][j] <= '9'){
            	p[s[i][j] - '0'].pb({i, j});
			}
                
        }
    }
    cout << bfs(sta, end) << endl;
    return 0;
}