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

来源:互联网 发布:中捷代购好还是淘宝好 编辑:程序博客网 时间:2024/04/28 11:19

来源: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