题目意思 :
给个 n 行 m 列的迷宫, 迷宫里面有一些珠宝(最多10个), 用 'A' 到 'J' 表示,'*'表示墙, '.'表示空白道路, ‘@’代表起点,'<'代表出口,问:在能给定时间限制下,最多能收集多少价值的珠宝
题解:
此题我用的是 bfs + 状态压缩, bfs大家都熟悉, 那么什么是状态压缩呢, 简单的说: 状态压缩就是把一个复杂的状态压缩成一个数字, 在二进制的情况下,比如此题: 用二进制的第(1-10)位为1代表有第 A - J 种珠宝,那么一下为每种珠宝的二进制表示:
珠宝编号 | 二进制 | 十进制表示 |
1 | 0000000001 | 1 |
2 | 0000000010 | 2 |
3 | 0000000100 | 4 |
4 | 0000001000 | 8 |
5 | 0000010000 | 16 |
6 | 0000100000 | 32 |
7 | 0001000000 | 64 |
8 | 0010000000 | 128 |
9 | 0100000000 | 256 |
10 | 1000000000 | 512 |
那么再分析一下此题, 我们在bfs的时候, 用vis[i][j][state]来表示各个状态的标记,i和j代表所处的位置, state代表该位置时所拥有的珠宝。那么vis[i][j][state] = 1 代表有过此状态了 不能入队列了,接下来就当作bfs强撸去吧。
代码: ps: 用这种方法 + 优化才险过啊,900多ms.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 50 + 10;
int vis[maxn][maxn][(1<<10)+1], score[maxn];
char maze[maxn][maxn];
int n, m, L, W, ans, dir[][2] = {{0,1},{0,-1},{1,0},{-1,0}};
struct Way{
int x, y, step, val, state;
Way(int x = 0, int y = 0, int step = 0, int val = 0, int state = 0) :
x(x), y(y), step(step), val(val), state(state) {}
}now, nxt, str;
bool bfs()
{
queue<Way> Q;
Q.push(str);
memset(vis, 0, sizeof(vis));
vis[str.x][str.y][0] = 1;
while (!Q.empty())
{
now = Q.front(); Q.pop();
if (now.step > L) break;
if (maze[now.x][now.y] == '<') {
ans = max(ans, now.val);
}
for (int i = 0; i < 4; i++) {
nxt = now;
nxt.step += 1, nxt.x += dir[i][0], nxt.y += dir[i][1];
int x = nxt.x, y = nxt.y;
if (!(x >= 0 && x < n && y >= 0 && y < m && maze[x][y] != '*')) continue;
if (maze[nxt.x][nxt.y] >= 'A' && maze[nxt.x][nxt.y] <= 'J') {
if ((nxt.state & (1<<(maze[nxt.x][nxt.y]-'A'))) == 0) {
nxt.state |= (1<<(maze[nxt.x][nxt.y]-'A'));
nxt.val += score[maze[nxt.x][nxt.y]-'A'];
}
}
if (!vis[nxt.x][nxt.y][nxt.state]){
Q.push(nxt);
vis[nxt.x][nxt.y][nxt.state] = 1;
}
}
}
if (ans != -1) return true;
else return false;
}
int main()
{
// freopen("/Users/apple/Desktop/in.txt", "r", stdin);
int t, kase = 0; scanf("%d", &t);
while (t--)
{
scanf("%d%d%d%d", &m, &n, &L, &W);
for (int i = 0; i < W; i++) {
scanf("%d", &score[i]);
}
for (int i = 0; i < n; i++) {
scanf("%s", maze[i]);
for (int j = 0; j < m; j++) {
if (maze[i][j] == '@') {
str = Way(i, j, 0, 0, 0);
}
}
}
ans = -1;
printf("Case %d:\n", ++kase);
if (bfs()) {
printf("The best score is %d.\n", ans);
}
else {
printf("Impossible\n");
}
if (t) printf("\n");
}
return 0;
}