ZOJ 1649 && HDU 1242 Rescue (BFS + 优先队列)

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.)

Input

First line contains two integers stand for N and M.

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.

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."

Sample Input

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........

Sample Output

13


解析:

广搜必须都是1个时间才能搜,才能保证这个BFS树是等距离向外伸展的,而这个不是等距离的,所以需要一些处理。

1、我的方法是,找到天使后,把时间比下大小,最后输出最小的。需要优化,只这么做的话,会TLE的,如果走过一个格子,这个格子存走过时候的时间,下次再走到这个格子,如果时间比格子里的短,就入队,否则,就不用入队了。20MS。

2. 优先队列+BFS  因为等距离的BFS的话,队列里的time值是从小往大排的,那直接用优先队列就可以了丫  0MS


代码及详细解析如下:

方法 I :
/****ZOJ 1649****/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <set>
#include <queue>
#include <algorithm>
#define MAXN 210
#define INF 1000000    //不要太大,太大结果错误
#define RST(N)memset(N, 0, sizeof(N))
using namespace std;

struct
{
    int x, y;
    int step;
    int time;
}q[1000000];

char Map[MAXN][MAXN];     //地图
int Min[MAXN][MAXN];      //走到每个位置所需的最小时间
int front, rear, res;
int n, m, Sx, Sy, Ex, Ey;
const int dx[] = {-1, 0, 1, 0};     //方向数组
const int dy[] = {0, 1, 0, -1};

bool check(int x, int y)    //走下一步的条件
{
    return x>=0 && y>=0 && x<n && y<m && Map[x][y]!='#';
}

void Init()
{
    front = rear = 0;
    memset(Min, INF, sizeof(Min));   //初始化Min
    Min[Sx][Sy] = 0;
    q[rear].x = Sx, q[rear].y = Sy;
    q[rear].time = 0, q[rear++].step = 0;  //将起始position加入队列
}

int main(int argc, char *argv[])
{
    while(~scanf("%d %d", &n, &m)) {
        for(int i=0; i<n; i++) {
            scanf("%s", Map[i]);
            for(int j=0; Map[i][j]; j++) {
                if(Map[i][j] == 'a') { Ex=i, Ey=j; }     //记录终点position
                else if(Map[i][j] == 'r') { Sx=i, Sy=j; }   //记录起始position
            }
        }
        Init();      //个别数据初始化
        while(front < rear) {     //当队列不为空
            int px = q[front].x;
            int py = q[front].y;   //current position
            for(int i=0; i<4; i++) { 
                int xx = px + dx[i];
                int yy = py + dy[i];
                //printf("xx = %d  yy = %d\n", xx, yy);
                if(check(xx, yy)) {
                    //printf("Matched xx = %d, yy = %d\n", xx, yy);
                    //v[xx][yy] = 1;
                    int qt = q[front].time + 1;
                    if(Map[xx][yy] == 'x') qt++;   //如果是警卫,杀死,时间+1
                    if(qt < Min[xx][yy]) {        //如果这种走法比之前走到该位置所花的时间少,则加入队列,否则不用加入队列
                        Min[xx][yy] = qt;
                        q[rear].x = xx, q[rear].y = yy;
                        q[rear].step = q[front].step + 1;
                        q[rear++].time = qt;
                    }
                    //printf("Matched cur_char = %c\n", Map[px][py]);
                    //printf("Matched next_pos_char = %c\n", Map[xx][yy]);
                    //printf("Matched cur_step = %d, cur_time = %d\n", q[front].step, q[front].time);
                    //printf("Matched step = %d, time = %d\n", q[rear].step, q[rear].time);
                }
            }
            front++;
        }
        if(Min[Ex][Ey] < INF) printf("%d\n", Min[Ex][Ey]);
        else puts("Poor ANGEL has to stay in the prison all his life.");
    }
    return 0;
}


方法 II :
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <limits.h>
#include <set>
#include <queue>
#include <algorithm>
#define MAXN 210
#define RST(N)memset(N, 0, sizeof(N))
using namespace std;

typedef struct Node
{
    int x, y;
    int time;
}Node;

Node start;
priority_queue <Node> pq;
char Map[MAXN][MAXN];
int v[MAXN][MAXN], n, m, res;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};

bool operator < (Node a, Node b)
{
    return a.time > b.time;
}

bool check(int x, int y)
{
    return x>=0 && y>=0 && x<n && y<m && Map[x][y]!='#' &&!v[x][y];
}

int BFS()
{
    Node cur;
    int xx, yy, px, py, T;
    while(!pq.empty()) {
        cur = pq.top(), pq.pop();
        px = cur.x, py = cur.y, T = cur.time;
        for(int i=0; i<4; i++) {
            xx = px + dx[i], yy = py + dy[i];
            if(check(xx, yy)) {
                v[xx][yy] = 1;
                if(Map[xx][yy] == 'a') return T+1;      //基友见面,返回
                cur.x = xx, cur.y = yy, cur.time = T+1;
                if(Map[xx][yy] == 'x') cur.time++;     //打死警卫,时间+1
                pq.push(cur);     //入队
            }
        }
    }
    return -1;
}

int main(int argc, char *argv[])
{
    while(~scanf("%d %d", &n, &m)) {
        RST(v);
        while(!pq.empty()) pq.pop();   //清空队列
        for(int i=0; i<n; i++) {
            scanf("%s", Map[i]);
            for(int j=0; j<m; j++) {
                if(Map[i][j] == 'r') {    //记录初始position
                    start.x = i, start.y = j;
                    start.time = 0;
                    pq.push(start);    //入队
                    v[i][j] = 1;
                }
            }
        }
        res = BFS();
        if(res != -1) printf("%d\n", res);
        else puts("Poor ANGEL has to stay in the prison all his life.");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个使用优先队列(priority queue)的题目,可以使用C++ STL中的优先队列来实现。 以下是样例代码: ```c++ #include <iostream> #include <queue> // 包含 priority_queue 头文件 using namespace std; int main() { int n; while (cin >> n) { priority_queue<int, vector<int>, greater<int>> pq; // 定义小根堆 for (int i = 0; i < n; i++) { int x; cin >> x; pq.push(x); // 将元素加入优先队列 } int ans = 0; while (pq.size() > 1) { // 只要队列中还有两个及以上元素 int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); ans += a + b; pq.push(a + b); // 新元素入队 } cout << ans << endl; } return 0; } ``` 在这个代码中,我们使用了C++ STL中的优先队列 `priority_queue`,它有三个模板参数: - `int`:表示队列中存储的元素类型是 `int`。 - `vector<int>`:表示队列内部使用 `vector` 作为基础容器。 - `greater<int>`:表示使用小根堆来存储元素。 在主函数中,我们首先读入元素,然后将它们加入到优先队列中。接着,我们依次取出队列中的两个最小元素,将它们相加并累加到答案中,然后将它们的和作为新元素加入到队列中。最后,当队列中只剩下一个元素时,输出答案。 需要注意的是,在使用小根堆时,我们要将模板参数 `greater<int>` 作为第三个参数传递给 `priority_queue`。如果不指定第三个参数,则默认使用大根堆。 另外,这里使用了 `while (cin >> n)` 的方式来不断读入测试用例,直到遇到输入结束符为止(比如EOF或者Ctrl+Z)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值