60ptsWAon#2#3#9#10
查看原帖
60ptsWAon#2#3#9#10
979584
zafa2023楼主2024/12/14 15:10
#include<bits/stdc++.h>
using namespace std;
void read(int &x){
	 int f=1;x=0;
	 char ch=getchar();
	 while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
	 while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
	 x*=f;
}
int n,m,a,b,ma[1001][1001],vis[1001][1001],que[100001][4],tot=0,head=0,wayx[4]={1,0,-1,0},wayy[4]={0,-1,0,1};
void bfs(){
	while(tot>=head){
	head++;
	vis[que[head][0]][que[head][1]]=1;
		for(int i=0;i<4;i++){
			int tx=que[head][0]+wayx[i],ty=que[head][1]+wayy[i];
			if(tx<1||ty<1||tx>n||ty>m)continue;
			if(vis[tx][ty])continue;
			vis[tx][ty]=1;
			ma[tx][ty]=ma[que[head][0]][que[head][1]]+1;
			que[++tot][1]=ty,que[tot][0]=tx;
		}
		
	}
}
int main()
{
	cin>>n>>m>>a>>b;
	for(int i=1;i<=a;i++){
		int x,y;
		read(x),read(y);
		vis[x][y]=1;
		tot++;
		que[tot][0]=x;que[tot][1]=y;
	}
	bfs();
	for(int i=1;i<=b;i++){
		int x,y;
		cin>>x>>y;
		printf("%d\n",ma[x][y]);
	}
	return 0;
}
2024/12/14 15:10
加载中...