hdu 5025 Saving Tang Monk 状态压缩dp+广搜

时间:2022-08-08 18:47:56

作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4092939.html

题目链接:hdu 5025 Saving Tang Monk 状态压缩dp+广搜

使用dp[x][y][key][s]来记录孙悟空的坐标(x,y)、当前获取到的钥匙key和打死的蛇s。由于钥匙具有先后顺序,因此在钥匙维度中只需开辟大小为10的长度来保存当前获取的最大编号的钥匙即可。蛇没有先后顺序,其中s的二进制的第i位等于1表示打死了该蛇,否则表示没打死。然后进行广度优先搜索即可,需要注意的是即使目前没有拿到第k-1把钥匙,也可以经过房间k或唐僧,只不过无法获取钥匙k和救唐僧而已。

代码如下:

 #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <queue>
#include <limits.h>
#define MAXN 101
#define MAXM 10
using namespace std;
int dir[][]={{, }, {, -}, {-, }, {, }};
char map[MAXN][MAXN];
int bin[] = {, , , , , , , , , , , , };
int dp[MAXN][MAXN][][];
int n, m;
class state
{
public:
int x, y, step, key, s;
};
state start, ed;
void solve()
{
memset(dp, -, sizeof(dp));
queue<state> qu;
qu.push(start);
int res = INT_MAX;
while( qu.size() > )
{
state cur = qu.front();
qu.pop();
for( int i = ; i < ; i++ )
{
if( cur.x == ed.x && cur.y == ed.y && cur.key== m )
{
res = min(res, cur.step);
continue;
}
state next;
next.x = cur.x+dir[i][];
next.y = cur.y+dir[i][];
next.key = cur.key;
next.s = cur.s;
next.step = cur.step;
if( next.x < || next.x >= n || next.y < || next.y >= n )//出界
{
continue;
}
char tmp = map[next.x][next.y];
if( tmp == '#' )//陷阱
{
continue;
}
if( tmp >= '' && tmp <= '' && cur.key >= tmp-''- )//有钥匙
{
next.step = cur.step+;
next.key = max(cur.key, tmp - '');
next.s = cur.s;
}
else if( tmp >= 'A' && tmp <= 'F')//蛇
{
if( cur.s/bin[tmp-'A']% == )
{
next.step = cur.step + ;
}
else
{
next.step = cur.step + ;
}
next.key = cur.key;
next.s = cur.s | bin[tmp-'A'];
}
else
{
next.key = cur.key;
next.step = cur.step+;
next.s = cur.s;
}
int dptmp = dp[next.x][next.y][next.key][next.s];
if( dptmp < )
{
dp[next.x][next.y][next.key][next.s] = next.step;
qu.push(next);
}
else if(dptmp > next.step)
{
dp[next.x][next.y][next.key][next.s] = next.step;
qu.push(next);
}
}
}
if( res == INT_MAX )
{
printf("impossible\n");
return;
}
printf("%d\n", res);
}
int main(int argc, char *argv[])
{
char tmp[MAXN+];
while()
{
scanf("%d%d", &n, &m);
if( n == && m == ) return ;
int sn = ;
for( int i = ; i < n ; i++ )
{
scanf("%s", tmp);
for( int j = ; j < n ; j++ )
{
if( tmp[j] == 'K' )
{
start.x = i;
start.y = j;
start.key = ;
start.step = ;
start.s = ;
}
else if( tmp[j] == 'T' )
{
ed.x = i;
ed.y = j;
}
else if( tmp[j] == 'S' )
{
map[i][j] = 'A'+sn;
sn++;
continue;
}
map[i][j] = tmp[j];
}
}
solve();
}
}