2016春季训练——搜索和优先队列

来源:HDU4198

BFS这里不用说,搜索去求一个最优情况的,往往使用BFS

下面分析一下优先队列的作用:

由于我们是要寻找到达的最小时间,这里面是有一个权值的不同的,所以我们不能简单的认为先出队列发就是我们权值最小的(队列中往往是这样,先出队列的是我们先到的),但是这一次不是这样,所以要对于权值进行排序。

代码(VJ):

#include <iostream>  
#include <cstdio>  
#include <cstring>  
#include <algorithm>  
#include <queue>  
using namespace std;  
const int MAXN = 510;  
struct Point {  
    int x, y, step;  
    bool operator< (Point const &a) const {  
        return step > a.step;  
    }  
}st,ed;  
char map[MAXN][MAXN];  
int vis[MAXN][MAXN];  
int dx[4]={1, -1, 0, 0};  
int dy[4]={0, 0, 1, -1};  
int n, m, k;  
void bfs() {  
    memset(vis, 0, sizeof(vis));  
    priority_queue<Point> q;  
    vis[st.x][st.y] = 1;  
    q.push(st);  
    while (!q.empty()) {  
        Point cur = q.top();  
        q.pop();  
        if (cur.x == 0 || cur.x == n-1 || cur.y == 0 || cur.y == m-1) {  
            printf("%d\n", cur.step+1);  
            return;  
        }  
        for (int i=0;i<4;i++) {  
            int nx = cur.x + dx[i];  
            int ny = cur.y + dy[i];  
            if (vis[nx][ny] || map[nx][ny] == '#')  
                continue;  
            if (nx >= 0 && nx < n && ny >= 0 && ny < m) {  
                vis[nx][ny] = 1;  
                Point tmp;  
                if (map[nx][ny] == '.') {  
                    tmp.x = nx, tmp.y = ny;  
                    tmp.step = cur.step + 1;  
                }  
                else if (map[nx][ny] == '@') {  
                    tmp.x = nx, tmp.y = ny;  
                    tmp.step = cur.step + k + 1;  
                }  
                q.push(tmp);  
            }  
        }  
    }  
}  
  
  
int main() {  
    int t;  
    scanf("%d", &t);  
    while (t--) {  
        scanf("%d%d%d", &n, &m, &k);  
        for (int i = 0; i < n; i++) {  
            scanf("%s", map[i]);  
            for (int j = 0; j < m; j++) {  
                if (map[i][j] == 'S') {  
                    map[i][j] = '.';  
                    st.x = i, st.y = j, st.step = 0;  
                }  
            }  
        }  
        bfs();  
  
    }  
    return 0;  
}  


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值