http://hihocoder.com/contest/acmicpc2018beijingonline 2018北京网络赛
#include <iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#include<queue>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=105;
char a[maxn][maxn];
int n,m;
int vis[maxn][maxn][6];
struct Node{
int x,y,step,B;
Node(int x,int y,int step=0,int B=0):x(x),y(y),step(step),B(B){}
bool operator<(const Node a)const{
return step>a.step;
}
};
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
void bfs(int x,int y){
memset(vis,0,sizeof(vis));
priority_queue<Node> pq;
pq.push(Node(x,y));
vis[x][y][0]=1;
int f=-1;
while(!pq.empty()){
Node p=pq.top();pq.pop();
x=p.x;y=p.y;
for(int i=0;i<4;i++){
int xt=x+dx[i];
int yt=y+dy[i];
int tB=p.B;
int ts=p.step+1;
if(xt<1||xt>n||yt<1||yt>m) continue;
if(a[xt][yt]=='#'&&tB<1) continue;
if(a[xt][yt]=='#'){
tB--;ts++;
}
if(a[xt][yt]=='B'&&tB<5) tB++;
if(a[xt][yt]=='P') ts--;
if(a[xt][yt]=='T'){
f=ts;break;
}
if(vis[xt][yt][tB]) continue;
vis[xt][yt][tB]=1;
pq.push(Node(xt,yt,ts,tB));
}
if(f!=-1) break;
}
printf("%d\n",f);
}
int main(){
while(scanf("%d %d",&n,&m)==2&&n&&m){
int i,j;
for(i=1;i<=n;i++){
scanf("%s",a[i]+1);
}
bool f=false;
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
if(a[i][j]=='S'){
bfs(i,j);
f=true;break;
}
}
if(f) break;
}
}
return 0;
}