题意巴拉巴拉我现在不想写~~
终于过了。。。手好生,好讨厌的感觉啊。。。。。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <cstdlib>
using namespace std;
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
struct node
{
int x,y,num,time,sta;
bool operator < (const node &a) const
{
return time>a.time;
}
};
char mp[105][105];
int vis[105][105][12][35];
priority_queue<node> q;
int n,m,sx,sy,ex,ey,cnt;
int bfs()
{
while(!q.empty())
q.pop();
q.push((node){sx,sy,0,0,0});
while(!q.empty())
{
node cur,next;
cur = q.top();
q.pop();
if(cur.x == ex && cur.y == ey && cur.num == m)
return cur.time;
if(vis[cur.x][cur.y][cur.num][cur.sta]!=-1)
continue;
vis[cur.x][cur.y][cur.num][cur.sta] = cur.time;
for(int i=0;i<4;i++)
{
next.x = cur.x+dx[i];
next.y = cur.y+dy[i];
if(mp[next.x][next.y]=='#') continue;
if(next.x<1 || next.x>n || next.y<1 || next.y>n) continue;
if((mp[next.x][next.y]>='1' && mp[next.x][next.y]<='1'+m) || mp[next.x][next.y]=='.' || mp[next.x][next.y]=='T' || mp[next.x][next.y]=='K')
{
if(mp[next.x][next.y]==cur.num+1+'0')
next.num = cur.num+1;
else next.num = cur.num;
next.time = cur.time+1;
next.sta = cur.sta;
}
else if(mp[next.x][next.y]>='A' && mp[next.x][next.y]<'A'+cnt)
{
int t = mp[next.x][next.y]-'A';
if(cur.sta&(1<<t))
{
next.sta = cur.sta;
next.time = cur.time+1;
}
else
{
next.sta = cur.sta|(1<<t);
next.time = cur.time+2;
}
next.num = cur.num;
}
q.push(next);
}
}
return -1;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0 && m==0)
break;
cnt = 0;
memset(vis,-1,sizeof(vis));
memset(mp,0,sizeof(mp));
for(int i=1;i<=n;i++)
{
scanf("%s",mp[i]+1);
for(int j=1;j<=n;j++)
{
if(mp[i][j]=='K')
{
sx = i;
sy = j;
}
else if(mp[i][j]=='S')
{
mp[i][j] = 'A'+cnt;
cnt++;
}
else if(mp[i][j]=='T')
{
ex = i;
ey = j;
}
}
}
/*for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cout<<mp[i][j]<<' ';
cout<<endl;
}*/
int ans = bfs();
if(ans==-1)
printf("impossible\n");
else printf("%d\n",ans);
}
return 0;
}