bzoj 1611: [Usaco2008 Feb]Meteor Shower [BFS]

t records the earliest time each grid was smashed, bfs(x, y, t) indicates that the current state is the (x, y) grid, and the time is t. Because of bfs, the t found first must be smaller than the one found later, so a grid can be searched once

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N=505,inf=1e9,dx[]={-1,1,0,0,0},dy[]={0,0,-1,1,0};
int n,m,t[N][N];
bool v[N][N];
struct qwe
{
    int x,y,t;
    qwe(int X=0,int Y=0,int T=0)
    {
        x=X,y=Y,t=T;
    }
};
queue<qwe>q;
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
inline bool ok(int x,int y,int z)
{
    return x>=0&&y>=0&&t[x][y]>z&&!v[x][y];
}
int main()
{
    n=read();
    for(int i=0;i<=500;i++)
        for(int j=0;j<=500;j++)
            t[i][j]=inf;
    for(int i=1;i<=n;i++)
    {
        int x=read(),y=read(),z=read();
        for(int j=0;j<5;j++)
            if(x+dx[j]>=0&&y+dy[j]>=0)
                t[x+dx[j]][y+dy[j]]=min(t[x+dx[j]][y+dy[j]],z);
    }
    q.push(qwe(0,0,0));
    v[0][0]=1;
    while(!q.empty())
    {
        int x=q.front().x,y=q.front().y,z=q.front().t;
        q.pop();
        if(t[x][y]==inf)
        {
            printf("%d\n",z);
            return 0;
        }
        for(int i=0;i<4;i++)
            if(ok(x+dx[i],y+dy[i],z+1))
            {
                v[x+dx[i]][y+dy[i]]=1;
                q.push(qwe(x+dx[i],y+dy[i],z+1));
            }
    }
    puts("-1");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325000350&siteId=291194637