ACM-ICPC2018北京网络赛 Saving Tang Monk II(bfs+剪枝)

题意:

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);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值