c++3TLE求改
查看原帖
c++3TLE求改
759152
yinbe楼主2023/9/5 08:16
#include<iostream>
#include<queue>
using namespace std;
int n,m,a,b,type_x,type_y,tx[250005],ty[250005],cnt,t[250005];
bool flag[505][505]={0};
struct path
{
	int x,y,step;
};
int _read()
{
	char c;
	int x=1,sum;
	while((c<'0'||c>'9')&&c!='-')
	{
		c=getchar();
	}
	if(c=='-')
	{
		x=-1;
	}
	else
	{
		sum=c-'0';
	}
	c=getchar();
	while(c>='0'&&c<='9')
	{
		sum=sum*10+(int)(c-'0');
		c=getchar();
	}
	return sum*x;
}
int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);
//	cout.tie(0);
	queue<path>q;
//	scanf("%d%d%d%d",&n,&m,&a,&b);
	n=_read();
	m=_read();
	a=_read();
	b=_read();
//	cin>>n>>m>>a>>b;
	for(int i=1;i<=a;i++)
	{
//		scanf("%d%d",&type_x,&type_y);
		type_x=_read();
		type_y=_read();
//		cin>>type_x>>type_y;
		q.push({type_y,type_x,0});
	}
	for(int i=1;i<=b;i++)
	{
//		scanf("%d%d",&ty[i],&tx[i]);
		ty[i]=_read();
		tx[i]=_read();
//		cin>>ty[i]>>tx[i];
	}
	while(!q.empty())
	{
		path c=q.front();
		q.pop();
		if(cnt==b)
		{
			break;
		}
		if(c.x<=0||c.y<=0||c.x>m||c.y>n)
		{
			continue;
		}
		if(flag[c.x][c.y])
		{
			continue;
		}
		for(int i=1;i<=b;i++)
		{
			if(c.x==tx[i]&&c.y==ty[i])
			{
				t[i]=c.step;
				cnt++;
				break;
			}
		}
		flag[c.x][c.y]=true;
		q.push({c.x+1,c.y,c.step+1});
		q.push({c.x-1,c.y,c.step+1});
		q.push({c.x,c.y+1,c.step+1});
		q.push({c.x,c.y-1,c.step+1});
	}
	for(int i=1;i<=b;i++)
	{
		printf("%d\n",t[i]);
//		cout<<t[i]<<"\n";
	}
	return 0;
}
2023/9/5 08:16
加载中...