您的位置:首页 > 产品设计 > UI/UE

POJ_2312_BFS:priority_queue -- Battle City

2014-05-07 19:05 274 查看
优先队列+BFS法
     用广搜的思想,只是在出队时做了处理,利用优先队列让队列中到起点的时间值最小的点先出队。该方法会用到优先队列的STL。

首先需要了解优先队列的使用规则:

优先队列中元素的比较规则默认是按元素的值从大到小排序的,就是说队列中最大的元素总是位于队首,所以出队时,并非按先进先出的原则进行,而是将当前队列中最大的元素出队。这点类似于给队列里的元素进行了从大到小的排序。当然,可以通过重载“<”操作符来重新定义比较规则。

重载“<”操作符的函数可以写在结构体里面,也可以写在结构体外面,写在结构体外面的时候,记得函数的参数要使用引用。。

第一种重载方法:

[cpp] view
plaincopy

struct node  

{  

    int x,y;  

    int step;  

};  

priority_queue<node>q;       //优先队列中元素的比较规则默认是按元素的值从大到小排序;  

  

bool operator<(const node &a,const node &b) //括号里面是const 而且还必须是引用  

{  

    return a.step>b.step;          //从小到大排序。重载小于号。因为默认是从大到小  

}  

第二种重载方法:

[cpp] view
plaincopy

struct node  

{  

    int x,y;  

    int time;  //定义一个优先队列  

    friend bool operator<(node a, node b)  

    {     //从小到大排序采用“>”号;如果要从大到小排序,则采用“<”号  

        return a.time> b.time;       //从小到大排序  

    }  

};    

priority_queue<node>q;       //优先队列中元素的比较规则默认是按元素的值从大到小排序;  

 
切记:从小到大排序采用“>”号;如果要从大到小排序,则采用“<”号;

/*
* POJ_2312_BFS:priority_queue -- Battle City
*
* I really like this BFS:priority_queue problem
*
* Author : a_clay  2014/05/06
*/
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");

using namespace std;
const int N = 305;
struct Point {
int x, y;
int steps;
};
bool operator < (const Point &a, const Point &b) {
return a.steps > b.steps;
}
char map

;
int n, m;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
bool ok(int x, int y) {
return (x >= 0 && x < m && y >= 0 && y < n);
}
Point you, tag;
int bfs() {
priority_queue<Point> Q;
Q.push(you);
Point t, tmp;
int xx, yy;
while (!Q.empty()) {
t = Q.top(); Q.pop();
for (int i = 0; i < 4; i++) {
xx = t.x + dx[i];
yy = t.y + dy[i];
if (!ok(xx, yy) || map[xx][yy] == 'R' || map[xx][yy] == 'S') {
continue;
}
if (xx == tag.x && yy == tag.y) return t.steps + 1;
tmp.x = xx;
tmp.y = yy;
if (map[xx][yy] == 'B') {
tmp.steps = t.steps + 2;
}
else tmp.steps = t.steps + 1;
map[xx][yy] = 'R';
Q.push(tmp);
}
}
return -1;
}
int main() {
while (scanf("%d%d", &m, &n), m|n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
if (map[i][j] == 'Y') {
you.x = i;
you.y = j;
you.steps = 0;
}
else if (map[i][j] == 'T') {
tag.x = i, tag.y = j;
}
}
}
printf("%d\n", bfs());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: