B
来源:互联网 发布:网络人软件 编辑:程序博客网 时间:2024/05/02 01:48
Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.
Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.
You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)
Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.
You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)
Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.
Process to the end of the file.
7 8#.#####.#.a#..r.#..#x.....#..#.##...##...#..............
13
题意:天使a被关在监狱里,天使的朋友r要去救他,'#'是墙不可走'.'是路可以走,每走一步耗费1秒钟,遇到‘x’士兵耗费2秒钟,输出r到达a的最短时间。采用优先队列和广搜
#include <cstdio>#include <queue>using namespace std;int n,m;char map[205][205];int sx,sy,ex,ey;//sx,sy存遇到'r'的,ex,ey存遇到'a'的int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//四个方向struct node{ int x,y,step; friend bool operator <(node a,node b) { return a.step>b.step;//小的优先 }}a,temp;//结构体用于自定义优先队列int bfs()//广搜{ a.x=sx; a.y=sy; a.step=0;//初始化从'r'开始走的位置 priority_queue<node>q; q.push(a);//入栈 while(!q.empty()) { a=q.top();//取栈顶赋予a q.pop(); if(a.x==ex&&a.y==ey) { return a.step;//判断是否遇到了'a' } for(int i=0;i<4;i++)//进行探索上下左右 { temp.x=a.x+dir[i][0]; temp.y=a.y+dir[i][1]; if(temp.x<n&&temp.x>=0&&temp.y<m&&temp.y>=0&&map[temp.x][temp.y]!='#')//判断是否能走 { if(map[temp.x][temp.y]=='.'||map[temp.x][temp.y]=='a') temp.step=a.step+1; else temp.step=a.step+2;//遇到士兵'x'需要两秒钟 map[temp.x][temp.y]='#';//走过的定义为墙,以免重复 q.push(temp);//继续入栈 } } } return 0;}int main(){ int ans; while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0;i<n;i++) scanf("%s",map[i]); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(map[i][j]=='r') { sx=i; sy=j; } if(map[i][j]=='a') { ex=i; ey=j; } } } ans=bfs(); if(ans) printf("%d\n",ans); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0;}