求调,状压+BFS
查看原帖
求调,状压+BFS
798157
emo_male_god楼主2023/12/18 16:51
#include <iostream>
#include <cstring>
#include <bitset>
#include <queue>

using namespace std;

inline char getch()
{
	static char buf[100005], *p1 = buf, *p2 = buf;
	return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100005, stdin), p1 == p2) ? EOF : *p1 ++ ;
}
template<typename Type>
inline void read(Type &x)
{
	char c; bool t;
	x = t = 0, c = getch();
	while (c < '0' || c > '9') t |= (c == '-'), c = getch();
	while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getch();
	x = t ? -x : x;
}

const int dx[] = {0, -1, 1, 0, 0};
const int dy[] = {0, 0, 0, -1, 1};
const int mapping[] = {0, 1, 0, 3, 2};
const int N = 11;

struct node
{
	int x, y, step, st;
};

int n, m, p, k, s;
bool st[N][N][N];
int g[N][N][4];
int key[N][N];

int bfs()
{
	queue<node> q;
	q.push({1, 1, 0, key[1][1]});
	st[1][1][key[1][1]] = true;

	while (!q.empty())
	{
		node u = q.front(), v;
		q.pop();

		if (u.x == n && u.y == m) return u.step;

		for (int i = 1; i <= 4; i = -~ i)
		{
			if (g[u.x][u.y][i - 1] != -1 && ((u.st >> g[u.x][u.y][i - 1]) & 1) == 0) continue;

			v = {u.x + dx[i], u.y + dy[i], u.step + 1};
			if (v.x < 1 || v.x > n || v.y < 1 || v.y > m) continue;

			v.st = u.st | key[v.x][v.y];

			if (st[v.x][v.y][v.st]) continue;

			st[v.x][v.y][v.st] = true;

			q.push(v);
		}
	}
	return -1;
}

int main()
{
	memset(g, -1, sizeof g);

	read(n), read(m), read(p), read(k);

	int x_, x__, y_, y__, type;
	for (int i = 1; i <= k; i = -~ i)
	{
		read(x_), read(y_), read(x__), read(y__), read(type);
		for (int j = 1; j <= 4; j = -~ j)
		{
			if (x_ + dx[j] == x__ && y_ + dy[j] == y__)
			{
				g[x_][y_][j - 1] = type;
				g[x__][y__][mapping[j]] = type;
				break;
			}
		}
	}
	read(s);
	for (int i = 1; i <= s; i = -~ i)
	{
		read(x_), read(y_), read(type);
		key[x_][y_] |= (1 << type);
	}
	printf("%d\n", bfs());
	return 0;
}
2023/12/18 16:51
加载中...