hdu 1026 BFS+优先队列
2015-07-25 21:55
253 查看
初看这道题就有一种感觉:这道题是搜索,但是普通的搜索绝对会TLE,但是又实在想不到什么好的方法做。百度了一下解题报告才知道这道题要加上优先队列的优化,先从时间小的结点开始扩展,这样的话保证每个结点只被搜索一次,并且被搜索到的时候对于这个结点来说,时间是最少的,所以我们只需扩展到右下角就停止搜索,这样的话时间复杂度就可以接受了。
这道题由于要输出路径,所以采用一个数组标记,最后用递归的方法进行输出。
有一点需要注意,由于有多组测试数据,所以每次要对优先队列进行初始化,就是因为没有初始化,我调了一个晚上!
这道题由于要输出路径,所以采用一个数组标记,最后用递归的方法进行输出。
有一点需要注意,由于有多组测试数据,所以每次要对优先队列进行初始化,就是因为没有初始化,我调了一个晚上!
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <queue> using namespace std; struct node { int ti,x,y; friend bool operator < (node a,node b) { return a.ti>b.ti; } }; priority_queue<node>q; int n,m,no; bool f[105][105]; char a[105][105]; struct ROUTE { int x,y; }r[105][105]; void bfs() { node w; w.x=0; w.y=0; w.ti=0; q.push(w); r[0][0].x=-1; r[0][0].y=-1; f[0][0]=1; w=q.top(); while ((w.x!=n-1)||(w.y!=m-1)) { int x=w.x,y=w.y,ti=w.ti+1; node step; if ((x>0)&&(a[x-1][y]!='X')&&(!f[x-1][y])) { f[x-1][y]=1; step.x=x-1; step.y=y; step.ti=ti; if (a[x-1][y]!='.') step.ti+=a[x-1][y]-'0'; q.push(step); r[x-1][y].x=x; r[x-1][y].y=y; } if ((x<n-1)&&(a[x+1][y]!='X')&&(!f[x+1][y])) { f[x+1][y]=1; step.x=x+1; step.y=y; step.ti=ti; if (a[x+1][y]!='.') step.ti+=a[x+1][y]-'0'; q.push(step); r[x+1][y].x=x; r[x+1][y].y=y; } if ((y>0)&&(a[x][y-1]!='X')&&(!f[x][y-1])) { f[x][y-1]=1; step.x=x; step.y=y-1; step.ti=ti; if (a[x][y-1]!='.') step.ti+=a[x][y-1]-'0'; q.push(step); r[x][y-1].x=x; r[x][y-1].y=y; } if ((y<m-1)&&(a[x][y+1]!='X')&&(!f[x][y+1])) { f[x][y+1]=1; step.x=x; step.y=y+1; step.ti=ti; if (a[x][y+1]!='.') step.ti+=a[x][y+1]-'0'; q.push(step); r[x][y+1].x=x; r[x][y+1].y=y; } q.pop(); if (q.empty()) break; w=q.top(); } if (q.empty()) {printf("God please help our poor hero.\n"); return;} printf("It takes %d seconds to reach the target position, let me show you the way.\n",w.ti); } void print (int q,int w) { int x=r[q][w].x,y=r[q][w].y; if (x<0) return; print(x,y); no++; printf("%d",no); printf("s:(%d,%d)->(%d,%d)\n",x,y,q,w); if (a[q][w]=='X') return; int z=0; if (a[q][w]!='.') z=a[q][w]-'0'; for (int i=0;i<z;i++) { no++; printf("%d",no); printf("s:FIGHT AT (%d,%d)\n",q,w); } } int main() { while (scanf("%d%d",&n,&m)!=EOF) { for (int i=0;i<n;i++) scanf("%s",a[i]); while (!q.empty()) q.pop(); memset(f,0,sizeof(f)); bfs(); no=0; if (!q.empty()) print(n-1,m-1); printf("FINISH\n"); } return 0; }
相关文章推荐
- 树常见的算法操作
- SQLServer 事务隔离级别与锁的申请和释放
- 关于visibility与display:none的jQuery问题
- 初学数据结构之二叉树
- vector::push_back 方法分析
- 去了大公司就能学到很牛的技术么?
- 差距啊。。。。。。。
- 浅析VS2010反汇编
- lamp-安装脚本-修订版1
- bresenham 画线算法
- 递归实现求Fibonacci数列的第n项
- 利用SQLmap 拿服务器shell
- wamp 修改www目录
- wamp 修改www目录
- Soldier and Badges(546B)
- zoj2388 Beat the Spread!
- 前端笔试题面试题系列(一)
- 浅谈 malloc/free 和 new/delete
- Python - 两个列表(list)组成字典(dict)
- linux 进程控制理论基础