优先队列解决广搜的问题
2014-09-22 19:50
513 查看
点击打开链接
题目大意:从p走到g,如果是#,则不能走,如果是“.”,则需要时间加1,如果是“x”,则时间加2,如果是“X”,则时间加3,问从p到g最少需要多少时间,如果不能到达,则输出-1。
方法:用一个优先队列,每次从里面选出时间最少时间,然后算走到四个方向的时间。
题目大意:从p走到g,如果是#,则不能走,如果是“.”,则需要时间加1,如果是“x”,则时间加2,如果是“X”,则时间加3,问从p到g最少需要多少时间,如果不能到达,则输出-1。
方法:用一个优先队列,每次从里面选出时间最少时间,然后算走到四个方向的时间。
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <queue> using namespace std; struct pp { int x,y; int step; pp(){} pp(int xx, int yy, int tt): x(xx),y(yy),step(tt){} bool operator < (const pp &a)const{ return step > a.step; } }; priority_queue<pp> qq; int d[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; bool flag[60][60]; int main(){ int T, cas, i, n, m, j; int stx, sty, enx, eny; char ch[60][60]; scanf("%d", &T); for(cas = 1; cas <= T; cas++){ scanf("%d%d",&n,&m); getchar(); memset(flag, 0, sizeof(flag)); for(i = 0; i < n; i++) scanf("%s",ch[i]); for(i = 0; i < n; i++){ for(j = 0 ;j < m; j++){ if(ch[i][j] == 'p'){ stx = i; sty = j; } else if(ch[i][j] == 'g'){ enx = i; eny = j; } } } //因为是多组数据,所以每一次都要用这样的方式清空 while(!qq.empty()){ qq.pop(); } qq.push(pp(stx, sty, 0)); flag[stx][sty] = 1; int cont = 0; pp cur; bool temp = 0; while(!qq.empty()){ cur = qq.top(); cont = cur.step; //用qq.top()去走,则需要将首元素去掉,然后再走 qq.pop(); for(i = 0; i < 4; i++){ int xxx = cur.x + d[i][0]; int yyy = cur.y + d[i][1]; if(xxx < 0 || xxx >= n) continue; if(yyy < 0 || yyy >= m) continue; if(ch[xxx][yyy] == '#') continue; if(flag[xxx][yyy] == 1) continue; if(xxx == enx && yyy == eny){ cont += 1; temp = 1; break; } if(ch[xxx][yyy] == 'x') qq.push(pp(xxx, yyy, cont+2)); else if(ch[xxx][yyy] == '.') qq.push(pp(xxx, yyy, cont+1)); else if(ch[xxx][yyy] == 'X') qq.push(pp(xxx, yyy, cont+3)); flag[xxx][yyy] = 1; } if(temp == 1) break; } if(!temp) printf("-1\n"); else printf("%d\n", cont); } return 0; }
相关文章推荐
- 最小优先队列 解决TopK问题
- 优先队列----解决排序问题
- 优先队列PriorityQueue实现 大小根堆 解决top k 问题
- 优先队列解决哈夫曼编码问题
- 51NOD 1163——最高的奖励(可用优先队列解决的贪心问题)
- 用“双优先队列”方法解决双/多指标的规划问题
- 优先队列实现 大小根堆 解决top k 问题
- C++优先队列解决哈夫曼(Huffmam)编码问题 (STL priority_queue)
- 用队列和栈解决球钟问题
- USACO解析Mixing Milk篇(使用STL优先队列解决)
- 好开心呀,能用自己学习知识去做作业了,也算是解决一些问题吧。操作系统实践作业:短作业优先(SJF)和先来先服务算法(FCFS)
- 用C++链式队列解决经典问题:舞伴问题!(带注释)
- 利用redis的list队列解决类似微博中msgbox表的性能问题
- 分支限界法解决装载问题之FIFO队列方式的总结
- 解决迷宫问题, 栈和队列
- 队列解决队员分配问题
- /九度OJ 教程30 优先队列解决哈夫曼树
- 回溯解决八数码问题(深度优先)
- 如何在 Exchange Server 2003 中使用队列查看器解决邮件流问题
- 用队列解决数据结构经典问题:杨辉三角形问题。