B - Security Guards Gym - 101954B -BFS+预处理

  • B - Security Guards

  •  Gym - 101954B 
  • 题意:一个人找了很多保安来给他看护着一个最大可能为5000*5000的二维图,给出每个保安所在点。
  • 然后询问给出一些出事地点问到达出事地点的最近保安的距离。保安移动规则:change each of  coordinates by 1, 0 or −1.
  • 思路:就是所有保安按照8个方向走,求每个点上最近的保安到达所需时间。普通BFS最初所有保安入队即可。
  • #include<bits/stdc++.h>
    using namespace std;
    #define inf 0x3f3f3f3f
    #define maxn 5555
    struct point
    {
        int x,y;
    } edge[maxn*100];
    bool vis[maxn][maxn];
    int dis[maxn][maxn];
    int n,q,x,y,ans,m1,m2,id;
    struct node
    {
        int x,y,step;
    } top,temp;
    int to[10][2]= {{1,0},{0,1},{0,-1},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};
    bool judge(int x,int y)
    {
        if(x<0||y<0||x>5000||y>5000||vis[x][y])
            return false;
        return true;
    }
    void bfs()
    {
        queue<node>q1,q2;
        for(int i=0; i<n; i++)
        {
            q1.push(node{edge[i].x,edge[i].y,0});
            vis[edge[i].x][edge[i].y]=1;
        }
        while(!q1.empty())
        {
            top=q1.front();
            q1.pop();
            dis[top.x][top.y]=top.step;
            for(int i=0; i<8; i++)
            {
                temp.x=top.x+to[i][0];
                temp.y=top.y+to[i][1];
                if(judge(temp.x,temp.y))
                {
                    temp.step=top.step+1;
                    vis[temp.x][temp.y]=1;
                    q1.push(temp);
                }
            }
        }
        return ;
    }
    int main()
    {
        scanf("%d%d",&n,&q);
        for(int i=0; i<n; i++)
            scanf("%d%d",&edge[i].x,&edge[i].y);
        bfs();
        while(q--)
        {
            scanf("%d%d",&x,&y);
            printf("%d\n",dis[x][y]);
        }
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/BePosit/article/details/84108502
今日推荐