3 1 K.S ##1 1#T 3 1 K#T .S# 1#. 3 2 K#T .S. 21. 0 0
5 impossible 8
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct S{
int x,y,step,state,snake;
bool operator<(const S &p) const
{
return step>p.step;
}
}t;
char mp[100][101];
bool vis[101][101][10][1<<5];
int nxt[4][2]={{0,1},{1,0},{-1,0},{0,-1}},idx[100][100];
int main()
{
int n,k,i,j,sx,sy,ex,ey,cnt,old;
while(~scanf("%d%d",&n,&k) && n)
{
for(i=0;i<n;i++) scanf("%s",mp[i]);
memset(vis,0,sizeof vis);
cnt=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(mp[i][j]=='K') sx=i,sy=j,mp[i][j]='.';
else if(mp[i][j]=='T') ex=i,ey=j,mp[i][j]='.';
else if(mp[i][j]=='S') idx[i][j]=cnt++;
}
}
priority_queue<S>que;
t.x=sx;
t.y=sy;
t.step=0;
t.state=0;
t.snake=0;
que.push(t);
while(!que.empty())
{
t=que.top();
if(t.x==ex && t.y==ey && t.state==k)
{
printf("%d\n",t.step);
break;
}
que.pop();
for(i=0;i<4;i++)
{
t.x+=nxt[i][0];
t.y+=nxt[i][1];
if(t.x>=0 && t.x<n && t.y>=0 && t.y<n && mp[t.x][t.y]!='#' && !vis[t.x][t.y][t.state][t.snake])
{
vis[t.x][t.y][t.state][t.snake]=1;
if(mp[t.x][t.y]=='.')
{
t.step++;
que.push(t);
t.step--;
}
else if(mp[t.x][t.y]=='S')
{
t.step++;
if(t.snake&(1<<idx[t.x][t.y])) que.push(t);//已经杀死
else//没有杀死
{
old=t.snake;
t.snake=(t.snake|(1<<idx[t.x][t.y]));
t.step++;
vis[t.x][t.y][t.state][t.snake]=1;
que.push(t);
t.snake=old;
t.step--;
}
t.step--;
}
else
{
if(mp[t.x][t.y]-'0'==t.state+1)
{
t.state++;
t.step++;
vis[t.x][t.y][t.state][t.snake]=1;
que.push(t);
t.state--;
t.step--;
}
else
{
t.step++;
que.push(t);
t.step--;
}
}
}
t.x-=nxt[i][0];
t.y-=nxt[i][1];
}
}
if(que.empty()) printf("impossible\n");
}
}HDU-5025-Saving Tang Monk(BFS+优先队列)
原文:http://blog.csdn.net/faithdmc/article/details/39433843