80分WA求助
查看原帖
80分WA求助
332914
happybob楼主2022/5/4 10:53
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <queue>
using namespace std;

const int N = 35;

unordered_map<char, int> mp;
char c[N][N];
int dis[N][N][5];
int h, w;

int dx[] = { 0, 0, -1, 1 };
int dy[] = { -1, 1, 0, 0 };

struct Node
{
	int x, y, cost, fx;
	/*
	fx = 1: 向左
	fx = 2: 向右
	fx = 3: 向上
	fx = 4: 向下
	*/
	Node(int _x, int _y, int _c, int _f) : x(_x), y(_y), cost(_c), fx(_f) {}
	bool operator<(const Node& p) const
	{
		return cost > p.cost;
	}
};

inline int turnleft(int x)
{
	if (x == 1) return 4;
	else if (x == 2) return 3;
	else if (x == 3) return 1;
	return 2;
}

inline int turnright(int x)
{
	if (x == 1) return 3;
	else if (x == 2) return 4;
	else if (x == 3) return 2;
	return 1;
}

int bfs(int sx, int sy, int ex, int ey)
{
	memset(dis, 0x3f, sizeof dis);
	mp['E'] = 2;
	mp['W'] = 1;
	mp['N'] = 3;
	mp['S'] = 4;
	int lb = mp[c[sx][sy]];
	dis[sx][sy][lb] = 0;
	priority_queue<Node> q;
	q.push(Node(sx, sy, 0, lb));
	while (!q.empty())
	{
		Node l = q.top();
		q.pop();
		int x = l.x, y = l.y;
		//cout << x << " " << y << endl;
		//system("pause");
		//if ((double)(clock()) / CLOCKS_PER_SEC >= 0.98 && x == ex && y == ey) return l.cost;
		bool ff = true;
		int nx = x + dx[l.fx - 1], ny = y + dy[l.fx - 1];
		if (nx >= 1 && nx <= h && ny >= 1 && ny <= w && (c[nx][ny] == '#' || c[nx][ny] == 'F'))
		{
			if (dis[nx][ny][l.fx] > l.cost) q.push(Node(nx, ny, l.cost, l.fx)), dis[nx][ny][l.fx] = l.cost, ff = false;
		}
		int nfx = turnleft(l.fx);
		nx = x + dx[nfx - 1], ny = y + dy[nfx - 1];
		if (nx >= 1 && nx <= h && ny >= 1 && ny <= w && (c[nx][ny] == '#' || c[nx][ny] == 'F'))
		{
			if (dis[nx][ny][nfx] > l.cost + 1) q.push(Node(nx, ny, l.cost + 1, nfx)), dis[nx][ny][nfx] = l.cost + 1, ff = false;
		}
		nfx = turnright(l.fx);
		nx = x + dx[nfx - 1], ny = y + dy[nfx - 1];
		if (nx >= 1 && nx <= h && ny >= 1 && ny <= w && (c[nx][ny] == '#' || c[nx][ny] == 'F'))
		{
			if (dis[nx][ny][nfx] > l.cost + 5) q.push(Node(nx, ny, l.cost + 5, nfx)), dis[nx][ny][nfx] = l.cost + 5, ff = false;
		}
		if (ff)
		{
			nfx = turnright(nfx);
			nx = x + dx[nfx - 1], ny = y + dy[nfx - 1];
			if (nx >= 1 && nx <= h && ny >= 1 && ny <= w && (c[nx][ny] == '#' || c[nx][ny] == 'F'))
			{
				if (dis[nx][ny][nfx] > l.cost + 10) q.push(Node(nx, ny, l.cost + 10, nfx)), dis[nx][ny][nfx] = l.cost + 10;
			}
		}
	}
	return min({ dis[ex][ey][1], dis[ex][ey][2], dis[ex][ey][3], dis[ex][ey][4] });
}

int main()
{
	scanf("%d %d", &h, &w);
	int sx = 0, sy = 0, ex = 0, ey = 0;
	for (int i = 1; i <= h; i++)
	{
		for (int j = 1; j <= w; j++)
		{
			cin >> c[i][j];
			if (c[i][j] == 'E' || c[i][j] == 'W' || c[i][j] == 'N' || c[i][j] == 'S')
			{
				sx = i;
				sy = j;
			}
			else if (c[i][j] == 'F')
			{
				ex = i;
				ey = j;
			}
		}
	}
	printf("%d\n", bfs(sx, sy, ex, ey));
	return 0;
}
2022/5/4 10:53
加载中...