题意:
S是起点,T是终点,B是加氧气点并花费一分钟,. 是任何条件都可以走并花费一分钟,#是要有氧气的情况下可以走但是要花费两分钟,P是可以少一分钟。
最多可以带5个氧气瓶,问从起点到终点最小花费时间。
题解:
每一点有6个状态,即 0氧气 到 5氧气,跑BFS维护每个点的每个状态只跑一次,用优先队列来控制先走时间花费最少的状态即可。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <stack>
#include <cmath>
#include <deque>
#include <queue>
#include <list>
#include <set>
#include <map>
#define mem(a, b) memset(a, b, sizeof(a))
#define pi acos(-1)
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
int step[4][2] = {{1,0}, {0,1}, {-1,0}, {0,-1}};
struct node{
int x, y, o, t;
node(){};
node(int _x, int _y, int _o, int _t){
x = _x;
y = _y;
o = _o;
t = _t;
}
bool operator <(const node &a) const {
return t > a.t;
}
};
char mapp[105][105];
int mark[105][105][10];
int sx, sy, n, m;
priority_queue<node> q;
int bfs(){
mem(mark, 0);
while (!q.empty()) {
q.pop();
}
q.push(node(sx, sy, 0, 0));
while(!q.empty()){
node p = q.top();
q.pop();
if(mapp[p.x][p.y] == 'T'){
return p.t;
}
if(mark[p.x][p.y][p.o]){
continue;
}
mark[p.x][p.y][p.o] = 1;
for(int i = 0; i < 4; i++){
int nx = p.x+step[i][0], ny = p.y+step[i][1];
if(nx >= n || nx < 0 || ny >= m || ny < 0){
continue;
}
if(mapp[nx][ny] == '#' && p.o){
q.push(node(nx, ny, p.o-1, p.t+2));
}
else if(mapp[nx][ny] == 'B'){
q.push(node(nx, ny, p.o+1 > 5 ? 5 : p.o+1, p.t+1));
}
else if(mapp[nx][ny] == 'P'){
q.push(node(nx, ny, p.o, p.t));
}
else if(mapp[nx][ny] == '.' || mapp[nx][ny] == 'T' || mapp[nx][ny] == 'S'){
q.push(node(nx, ny, p.o, p.t+1));
}
}
}
return -1;
}
int main(){
while(scanf("%d %d", &n, &m), n, m){
for(int i = 0; i < n; i++){
scanf("%s", mapp[i]);
for(int j = 0; j < m; j++){
if(mapp[i][j] == 'S'){
sx = i;
sy = j;
}
}
}
int ans = bfs();
printf("%d\n", ans);
}
}