zoukankan      html  css  js  c++  java
  • 血色先锋队【BFS】

    题目大意:

    给出k个起始点和t个结束点,求每个结束点距离任意一个起始点的最短马哈顿距离。
    Input

    5 4 2 3
    1 1
    5 4
    3 3
    5 3
    2 4
    

    Output

    3
    1
    3

    思路:

    裸的BFS,读入每个起始点的位置后就可以求出图中每一个点的最短马哈顿距离,求完之后再读入终点,O(1)输出即可。
    时间复杂度:O(nm)


    代码:

    #include <cstdio>
    #include <iostream>
    using namespace std;
    
    const int dx[]={0,0,0,-1,1};
    const int dy[]={0,1,-1,0,0};
    int n,m,k,t,x,y,a[1011][1011],state[10000011][5],head,tail,dis[1011][1011];
    
    void bfs() 
    {
        do
        {
            head++;
            for (int i=1;i<=4;i++)
            {
                int xx=state[head][1]+dx[i];
                int yy=state[head][2]+dy[i];
                if (a[xx][yy]||xx<1||xx>n||yy<1||yy>m) continue;  //出界或已经到达
                tail++;
                a[xx][yy]=1;
                state[tail][1]=xx;
                state[tail][2]=yy;
                dis[xx][yy]=dis[state[head][1]][state[head][2]]+1;  //记录最短距离
            }
        }
        while (head<tail);
    }
    
    int main()
    {
        scanf("%d%d%d%d",&n,&m,&k,&t);
        for (int i=1;i<=k;i++)
        {
            scanf("%d%d",&x,&y);
            tail++;
            state[tail][1]=x;
            state[tail][2]=y;
            a[x][y]=1;
        }
        bfs();
        for (int i=1;i<=t;i++)
        {
            scanf("%d%d",&x,&y);
            printf("%d\n",dis[x][y]);
        }
        return 0;
    }
  • 相关阅读:
    模拟ssh远程执行命令
    基于UDP协议的套接字编程
    TCP三次握手,四次挥手
    基于TCP协议的套接字编程
    osi七层协议
    Python之__class__.__module__,__class__.__name__
    异常处理
    单例模式
    类方法__setattr__,__delattr__,__getattr__
    反射(hasattr,getattr,delattr,setattr)
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998822.html
Copyright © 2011-2022 走看看