跳到正文

题解

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

ycy1124约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年11月11日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟
题目
P14469

版本

  1. v2当前
  2. v1

思路

考虑对于原本题目中的可以移动任意格的限制,我们可以转换为每次移动一格,如果和上一次移动的方向相同就无需花费。

我们只需要记录到达当前节点时所面朝的方向,然后直接 Dijkstra 即可。

代码

C++
#include<bits/stdc++.h>
using namespace std;

const int N = 1005;

struct Node{
	int x, y, op, w;
}b[N * N * 9];

int n, m, tot, dis[N][N][9], px[8] = {0, 0, 1, 1, 1, -1, -1, -1}, py[8] = {1, -1, 0, 1, -1, 0, 1, -1}, x[10], y[10];

struct node{
	int x, y;
};

node to[N][N];

char ch[N][N];

void work(int x) {
	if(x != 1 && b[x].w < b[x / 2].w) {
		swap(b[x], b[x / 2]);
		work(x / 2);
	}
}

void work1(int x) {
	if(x * 2 + 1 <= tot && b[x * 2 + 1].w < b[x].w && b[x * 2 + 1].w < b[x * 2].w) {
		swap(b[x * 2 + 1], b[x]);
		work1(x * 2 + 1);
	}
	else if(x * 2 <= tot && b[x * 2].w < b[x].w) {
		swap(b[x], b[x * 2]);
		work1(x * 2);
	}
}

__inline__ void bfs(Node p) {

	if(p.w > dis[p.x][p.y][p.op]) {
		return;
	}

	if(ch[p.x][p.y] >= '1' && ch[p.x][p.y] <= '9') {

		if(p.w < dis[to[p.x][p.y].x][to[p.x][p.y].y][8]) {
			dis[to[p.x][p.y].x][to[p.x][p.y].y][8] = p.w;
			b[++ tot] = {to[p.x][p.y].x, to[p.x][p.y].y, 8, p.w};
			work(tot);
		}
	}

	for(int i = 0; i < 8; i ++) {

		int xx = p.x + px[i], yy = p.y + py[i], ww = p.w + (p.op != i);

		if(xx < 1 || xx > n || yy < 1 || yy > n || ww >= dis[xx][yy][i] || ch[xx][yy] == '#') {
			continue;
		}

		dis[xx][yy][i] = ww;
		b[++ tot] = {xx, yy, i, ww};
		work(tot);
	}
}

int main () {

	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);

	cin >> n >> m;
	for(int i = 1; i <= n; i ++) {
		for(int j = 1; j <= m; j ++) {
			for(int k = 0; k <= 8; k ++) {
				dis[i][j][k] = 1e9;
			}
		}
	}

	for(int i = 1; i <= n; i ++) {
		for(int j = 1; j <= m; j ++) {

			cin >> ch[i][j];

			if(ch[i][j] == 'S') {
				b[++ tot] = {i, j, 8, 0};
			}

			if(ch[i][j] >= '1' && ch[i][j] <= '9') {
				if(x[ch[i][j] - '0']) {
					to[i][j] = {x[ch[i][j] - '0'], y[ch[i][j] - '0']};
					to[x[ch[i][j] - '0']][y[ch[i][j] - '0']] = {i, j};
				}
				else {
					x[ch[i][j] - '0'] = i, y[ch[i][j] - '0'] = j;
				}
			}
		}
	}

	while(tot) {
		Node u = b[1];
		swap(b[1], b[tot]);
		tot --;
		work1(1);
		bfs(u);
	}

	int ans = 1e9;

	for(int i = 1; i <= n; i ++) {
		for(int j = 1; j <= m; j ++) {
			if(ch[i][j] == 'E') {
				for(int k = 0; k <= 8; k ++) {
					ans = min(ans, dis[i][j][k]);
				}
			}
		}
	}

	if(ans == 1e9) {
		cout << -1;
		return 0;
	}

	cout << ans;

	return 0;
}
原文