POJ3669 Meteor Shower(BFS + 预处理)

题意:给出n各点的坐标及爆炸时间(每个点爆炸时都会同时殃及该点上下左右四个点),Bessie一开始在原点,求她至少走几步才能到达一个安全的位置不被炸死。

分析:用mp[][]存储每个位置最早的爆炸时间,然后bfs,当到达一个地方的mp[][]为inf的时候,意味着安全了。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<cstdio>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
#define maxn 400
typedef struct Node{
    ll x,y,t;
}node;
node A[maxn];
ll ans=0,cnt,m,t,mp[maxn][maxn],vis[maxn][maxn],x,y,z;
ll dir[4][2]={-1,0,1,0,0,1,0,-1};
int legal(ll x,ll y){
    return x>=0&&y>=0;
}

void bfs(ll x,ll y){
    memset(vis,0,sizeof(vis));
    node a;
    a.x=x,a.y=y,a.t=0;
    queue<node> que;
    que.push(a);
    vis[0][0]=1;
    while(!que.empty()){
        node b=que.front(); que.pop();
        ll x=b.x,y=b.y,t=b.t;

        if(mp[x][y]==inf){
            cout<<t<<endl;
            return ;
        }
        for(int i=0;i<4;i++){
            ll nx=x+dir[i][0];
            ll ny=y+dir[i][1];
            ll nt=t+1;
            if(legal(nx,ny)&&!vis[nx][ny]&&mp[nx][ny]>nt){
                node c;
                c.x=nx;
                c.y=ny;
                c.t=nt;
                que.push(c);
                vis[nx][ny]=1;
            }
        }
    }
    cout<<"-1"<<endl;
}
int main(){
    //scanf
    while(cin>>m){
        //mp[][]存储每一个点最早爆炸的时间 
        for(int i=0;i<maxn;i++)
            for(int j=0;j<maxn;j++) mp[i][j]=inf;

        for(int i=0;i<m;i++){
            scanf("%lld%lld%lld",&x,&y,&t);
            if(mp[x][y]>t){
                mp[x][y]=t;
            } 
            for(int j=0;j<4;j++){
                ll dx=x+dir[j][0],dy=y+dir[j][1];
                if(legal(dx,dy)&&mp[dx][dy]>t){
                    mp[dx][dy]=t;
                }
            }
        }
        //solve
        bfs(0,0);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37360631/article/details/81636911