BFS,優先隊列優化
阿新 • • 發佈:2018-09-23
獲得 ble pac 方向 str hint open mem puts
題意:
‘S‘ : 起點
‘T‘ : 終點
‘#‘ : 毒氣室
‘B‘ :氧氣
‘P‘:不消耗步數
每次經過毒氣室需要一瓶氧氣,氧氣可以重復獲得,但只能帶五瓶氧氣,問最少步數
solution:
HINT:多維狀態判重,多一維攜帶氧氣瓶數量
沒帶氧氣瓶的時候不能走毒氣室#
攜帶超過5個跳過氧氣B
相似題目:UVA816 Abbott‘s Revenge這題多一維方向
1 #include<bits/stdc++.h> 2 #include<iostream> 3 #include<cstdio> 4 #include<algorithm> 5View Code#include<vector> 6 #include<queue> 7 #include<cstring> 8 #define fi first 9 #define se second 10 #define mp make_pair 11 #define pb push_back 12 #define pw(x) (1ll << (x)) 13 #define sz(x) ((int)(x).size()) 14 #define all(x) (x).begin(),(x).end() 15 #define rep(i,l,r) for(int i=(l);i<(r);++i) 16#define per(i,l,r) for(int i=(r)-1;i>=(l);--i) 17 #define maxn 500005 18 #define eps 1e-9 19 #define PIE acos(-1) 20 #define dd(x) cout << #x << " = " << (x) << ", " 21 #define de(x) cout << #x << " = " << (x) << "\n" 22 #define endl "\n" 23 #defineINF 0x3f3f3f3f 24 using namespace std; 25 typedef double db; 26 typedef long long LL; 27 typedef vector<int> vi; 28 typedef pair<int, int> pii; 29 //---------------------- 30 int n,m; 31 char pic[105][105]; 32 bool vis[105][105][6]; 33 const int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; 34 struct Node{ 35 int x; 36 int y; 37 int d=0; 38 int cnt=0; 39 bool operator<(const Node& a)const{ 40 return d>a.d; 41 } 42 }start,u,v; 43 int cnt; 44 bool check(Node v) 45 { 46 return v.x>=0&&v.x<n&&v.y>=0&&v.y<m; 47 } 48 int bfs(int x,int y)//把#當路障,找氧氣瓶 49 { 50 memset(vis,0,sizeof(vis)); 51 priority_queue<Node>q; 52 vis[x][y][0]=1; 53 start.x=x;start.y=y;start.d=0;start.cnt=0; 54 q.push(start); 55 while(!q.empty()) 56 { 57 u=q.top();q.pop(); 58 if(pic[u.x][u.y]==‘T‘){return u.d;} 59 rep(i,0,4){ 60 v=u; 61 v.x+=dir[i][0]; 62 v.y+=dir[i][1]; 63 if(!check(v))continue; 64 if(pic[v.x][v.y]==‘#‘){ 65 if(v.cnt>=1)v.cnt--,v.d++; 66 else continue; 67 } 68 else if(pic[v.x][v.y]==‘B‘){ 69 if(v.cnt>=5)continue; 70 else v.cnt++; 71 } 72 else if(pic[v.x][v.y]==‘P‘)v.d--; 73 v.d++; 74 if(vis[v.x][v.y][v.cnt])continue; 75 vis[v.x][v.y][v.cnt]=1; 76 // dd(v.x+1);dd(v.y+1);dd(pic[v.x][v.y]);dd(v.cnt);de(v.d); 77 q.push(v); 78 } 79 } 80 return INF; 81 } 82 int main() 83 { 84 // ifstream cin("in.txt"); 85 while(cin>>n>>m,n+m){ 86 int ans=INF; 87 int ok=0; 88 rep(i,0,n)rep(j,0,m){ 89 cin>>pic[i][j]; 90 } 91 rep(i,0,n)rep(j,0,m)if(pic[i][j]==‘S‘) 92 { 93 ans=bfs(i,j); 94 goto here; 95 } 96 here:; 97 if(ans!=INF)printf("%d\n",ans); 98 else puts("-1"); 99 } 100 return 0; 101 }
BFS,優先隊列優化