hdu 1242 Rescue(优先队列 && 广搜BFS)
2016-12-09 16:52
423 查看
[align=center] Rescue[/align]
[align=left]原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242[/align]
[align=left]题意:Angel被关押在牢里,Angel的朋友要去救Angel,给出Angel的朋友的位置(起点),求到达Angel的位置(终点)最小需要用多少时间。(路上遇见守卫,打败守卫需要花费1m)[/align]
[align=left]思路:用BFS来搜索最短时间,注意 可能遇见守卫所以需要用到优先队列,让时间短的先出队。[/align]
另外特别注意可能有多个'r',因此可以让终点为起点,找到时间最短的'r'。(然而 题目的后台数据可能只有一个r
)
[align=left]代码:[/align]
[align=left]原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242[/align]
[align=left]题意:Angel被关押在牢里,Angel的朋友要去救Angel,给出Angel的朋友的位置(起点),求到达Angel的位置(终点)最小需要用多少时间。(路上遇见守卫,打败守卫需要花费1m)[/align]
[align=left]思路:用BFS来搜索最短时间,注意 可能遇见守卫所以需要用到优先队列,让时间短的先出队。[/align]
另外特别注意可能有多个'r',因此可以让终点为起点,找到时间最短的'r'。(然而 题目的后台数据可能只有一个r
)
[align=left]代码:[/align]
#include<stdio.h> #include<string.h> #include<queue> using namespace std; char a[202][202]; bool vis[202][202]; int to[4][2]= {0,1,0,-1,1,0,-1,0};//方向 int n,m; struct node { int x,y,s; friend bool operator < (node a,node b)//重载运算符,使时间小的先出队 { return a.s>b.s; } }; int bfs(int x,int y) { node now,next; priority_queue<node>w; now.x=x,now.y=y,now.s=0;//将起点放入队列 w.push(now); vis[x][y]=1; while(!w.empty()) { now=w.top();//取出队列的头 if(a[now.x][now.y]=='r')//找到终点 return now.s; w.pop(); for(int i=0; i<4; i++) { int cnt=now.x+to[i][0],ans=now.y+to[i][1]; if(cnt>=0&&ans>=0&&cnt<n&&ans<m&&a[cnt][ans]!='#'&&!vis[cnt][ans]) { vis[cnt][ans]=1; next.x=cnt,next.y=ans,next.s=now.s+1; if(a[cnt][ans]=='x') next.s++; w.push(next); } } } return 0; } int main() { while(~scanf("%d%d",&n,&m)) { memset(vis,0,sizeof(vis)); int i,j,x,y; for(i=0; i<n; i++) { scanf("%s",&a[i]); for(j=0; j<m; j++) if(a[i][j]=='a')//找到起点 x=i,y=j; } int k=bfs(x,y); if(k) printf("%d\n",k); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; }
相关文章推荐
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- hdu 1242 Rescue(优先队列 && 广搜BFS)
- Macros for Build Commands and Properties
- iOS UITextField实现输入手机号时自动添加空格
- UISwitch - 开关按钮 的使用详解
- Vue 2.0 + Vue Router + Vuex
- ElementUI之表单验证、数据绑定、路由跳转
- easyui toolbar 动态显示与隐藏
- EasyUI Tree 树
- java轻量级IOC框架Guice
- OpenGL ES2.0 Programming Guide - chapter 2:Hello Triangle: An OpenGL ES2.0 example
- 视觉问答(Visual Question Answering)论文初步整理
- 用Mysql5.6出现时间问题Incorrect datetime value: '' for column 'createtime'
- UIPickView和UIDatePicker(了解)