跳到正文

题解

题解:P12684 【MX-J15-T4】叉叉学习魔法

__liujy约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟
题目
P12684

版本

  1. v1当前

考虑广搜优化。

先跑第一个答案,再跑第二个答案。

再优化这个操作,建一个双端队列,跑第一个答案:如果当前走的是斜线,那么只需要花魔法,则,将它放在双端队列前面,因为它的步数较少;否则跑的是直线,则,将它放在双端队列后面,因为它的步数较多。

再跑第二个答案,若跑的是斜线那么要花魔法,若跑的是直线不用花魔法,但是前提条件是当前步数等于最少步数。

C++
#include<bits/stdc++.h>
using namespace std;
#define ri register int
inline int read(){
    int ans = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9'){
        f = (ch == '-' ? -1 : f);
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9'){
        ans = (ans << 1) + (ans << 3) + (ch ^ 48);
        ch = getchar();
    }
    return ans * f;
}
inline string Read(){
	string ans = "";
	char ch = getchar();
	while(ch == ' ' || ch == '\n') ch = getchar();
	while(ch != ' ' && ch != '\n'){
		ans += ch;
		ch = getchar();
	}
	return ans;
}
inline char RRead(){
	char ch = getchar();
	while(ch == ' ' || ch == '\n') ch = getchar();
	return ch;
}
inline void print(int x){
    if(x < 0){
        x = -x;
        putchar('-');
    }
    if(x > 9) print(x / 10);
    putchar(x % 10 ^ 48);
}
inline void write(int x){
    print(x);
    putchar(' ');
}

const int N = 5005;

typedef pair<int, int> PII;

int n, m, bx, by, ex, ey, dir[8][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}, f[N][N], g[N][N];
char a[N][N];
deque<PII>q;

int main(){
	n = read(), m = read();
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++){
			a[i][j] = RRead();
		}
	}

	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++){
			if(a[i][j] == 'X') bx = i, by = j;
			else if(a[i][j] == 'W') ex = i, ey = j;
		}
	}

	q.push_front(make_pair(bx, by));
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++){
			f[i][j] = 0x7f7f7f7f;
		}
	}
	f[bx][by] = 0;
	while(q.size()){
		int x = q.front().first, y = q.front().second;
		q.pop_front();

		for(ri i = 0; i < 8; i++){
			int tx = x + dir[i][0], ty = y + dir[i][1];

			if(tx >= 1&& tx <= n && ty >= 1 && ty <= m && a[tx][ty] != '#'){
				if(f[tx][ty] <= f[x][y] + (i < 4)) continue;
				f[tx][ty] = f[x][y] + (i < 4);

				if(i < 4) q.push_back(make_pair(tx, ty));
				else q.push_front(make_pair(tx, ty));
			}
		}
	}

	if(f[ex][ey] == 0x7f7f7f7f){
		write(-1);
		write(-1);
		return 0;
	}
	write(f[ex][ey]);

	q.push_front(make_pair(bx, by));
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++){
			g[i][j] = 0x7f7f7f7f;
		}
	}
	g[bx][by] = 0;
	while(q.size()){
		int x = q.front().first, y = q.front().second;
		q.pop_front();

		for(ri i = 0; i < 8; i++){
			int tx = x + dir[i][0], ty = y + dir[i][1];
			if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && a[tx][ty] != '#' && f[tx][ty] == f[x][y] + (i < 4)){
				if(g[tx][ty] <= g[x][y] + (i >= 4)) continue;
				g[tx][ty] = g[x][y] + (i >= 4);

				if(i >= 4) q.push_back(make_pair(tx, ty));
				else q.push_front(make_pair(tx, ty));
			}
		}
	}

	write(g[ex][ey]);

	return 0;
}
原文