POJ 2312 Battle City (BFS状态搜索)

来源:互联网 发布:汕头网店美工培训sina 编辑:程序博客网 时间:2024/05/16 06:28

题意:

。。。

思路:

R和S是不能走的,遇到B时发射子弹和移动可以合并成一个代价为2的移动。

我们的状态是 [ 当前的位置, 已经消耗的时间 ]

状态用优先队列保存, 每次取出, 剪枝,  扩展

因为优先队列中取出的始终是 time 最小的状态,所以判断到达了终点就可以退出。

//#include<bits/stdc++.h>#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <vector>#include <queue>#include <stack>#include <cassert>#include <algorithm>#include <cmath>#include <climits>#include <set>#include <map>using namespace std;#define SPEED_UP iostream::sync_with_stdio(false);#define FIXED_FLOAT cout.setf(ios::fixed, ios::floatfield);#define rep(i, s, t) for(int (i)=(s);(i)<=(t);++(i))#define urep(i, s, t) for(int (i)=(s);(i)>=(t);--(i))typedef long long LL;const int Maxn = 305;char mm[Maxn][Maxn];int n, m, t[Maxn][Maxn], sx, sy, ex, ey;const int dx[] = {-1, 1, 0, 0};const int dy[] = {0, 0, -1, 1};struct st{    int x;    int y;    int t;    st(int x, int y, int t):x(x), y(y), t(t){};    inline bool operator < (const st& rhs) const {        return t > rhs.t;    }};inline int check(int x, int y) {    return 0 <= x && x < n && 0 <= y && y < m;}void init() {    rep(i, 0, n-1) {        scanf("%s", mm[i]);        rep(j, 0, m-1) {            if (mm[i][j] == 'Y') sx = i, sy = j;            else if (mm[i][j] == 'T') ex = i, ey = j;        }    }}void solve() {    priority_queue<st> q;    //queue<st> q;    q.push( st(sx, sy, 0) );    rep(i, 0, n-1)        rep(j, 0, m-1) t[i][j] = INT_MAX;    int x, y, old_t;    t[sx][sy] = 0;    while (!q.empty()) {        st fr = q.top();q.pop();        x = fr.x, y = fr.y, old_t = fr.t;        if (x == ex && y == ey) {            break;            //continue;        }        int nx, ny, nt;        rep(i, 0, 3) {            nx = x + dx[i];            ny = y + dy[i];            nt = old_t + 1;            // skip ?            if (!check(nx, ny) || mm[nx][ny] == 'S' || mm[nx][ny] == 'R') continue;            if (mm[nx][ny] == 'B') ++nt;            if (nt >= t[ex][ey] || nt >= t[nx][ny]) continue;            t[nx][ny] = nt;            //cout << "going to " << nx << ", " << ny << endl;            //cout << "time = " << nt << endl;            q.push(st(nx, ny, nt));        }    }    if (t[ex][ey] == INT_MAX) {        printf("-1\n");    }    else {        printf("%d\n", t[ex][ey]);    }}int main() {#ifndef ONLINE_JUDGE    freopen("input.in", "r", stdin);#endif    //SPEED_UP    while (scanf("%d%d",&n, &m) != EOF && (m && n)) {        init();        if (sx == ex && sy == ey) cout << '0' << endl;        solve();    }    return 0;}


0 0
原创粉丝点击