求助WA on #2 & #8
查看原帖
求助WA on #2 & #8
914531
W2009y12n21楼主2024/10/9 20:44
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
queue<pair<int,int> >q;
int n,m;
int g[510][510];
bool vis[510][510];
int ld[100100][2];
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void bfs()
{
	while(!q.empty())
	{
		pair<int,int> p=q.front();
		if(p.second+d[0][1]<=n&&vis[p.first+d[0][0]][p.second+d[0][1]]==1)
		{
			q.push({p.first+d[0][0],p.second+d[0][1]});
			vis[p.first+d[0][0]][p.second+d[0][1]]=0;
			g[p.first+d[0][0]][p.second+d[0][1]]=g[p.first][p.second]+1;
		}
		if(p.second+d[1][1]>=1&&vis[p.first+d[1][0]][p.second+d[1][1]]==1)
		{
			q.push({p.first+d[1][0],p.second+d[1][1]});
			vis[p.first+d[1][0]][p.second+d[1][1]]=0;
			g[p.first+d[1][0]][p.second+d[1][1]]=g[p.first][p.second]+1;
		}
		if(p.first+d[2][0]<=m&&vis[p.first+d[2][0]][p.second+d[2][1]]==1)
		{
			q.push({p.first+d[2][0],p.second+d[2][1]});
			vis[p.first+d[2][0]][p.second+d[2][1]]=0;
			g[p.first+d[2][0]][p.second+d[2][1]]=g[p.first][p.second]+1;
		}
		if(p.first+d[3][0]>=1&&vis[p.first+d[3][0]][p.second+d[3][1]]==1)
		{
			q.push({p.first+d[3][0],p.second+d[3][1]});
			vis[p.first+d[3][0]][p.second+d[3][1]]=0;
			g[p.first+d[3][0]][p.second+d[3][1]]=g[p.first][p.second]+1;
		}
		q.pop();
	}
}
int main(){
//	freopen("P1332_2.in","r",stdin);
	cin>>n>>m;
	memset(vis,true,sizeof(vis));
	int a,b;
	cin>>a>>b;
	for(int i=1;i<=a;i++)
	{
		int x,y;
		cin>>x>>y;
		g[x][y]=0;
		q.push({x,y});
		vis[x][y]=0;
	}
	for(int i=1;i<=b;i++)
	{
		cin>>ld[i][0]>>ld[i][1];
	}
	bfs();
	for(int i=1;i<=b;i++)
	{
		cout<<g[ld[i][0]][ld[i][1]]<<endl;
	}
}
2024/10/9 20:44
加载中...