头像

欢迎来到我的博客

分享题解与总结

P2895 Meteor Shower S

P2895 Meteor Shower S

P2895 USACO08FEB Meteor Shower S - 洛谷

思路:

流星雨MeteorShower

边界:

题目样例点似乎没有t=0砸中(0,0)的情形

至少我不加特判if(e[sx][sy]==0){cout<<-1;return;}是可以AC的

注意:

  1. 数组初始化慎用memset,除非你初始化为0

    数组如果初始化为0——混淆t=0砸中的情况

    初始化为-1——在判断能不能走到某一方格时head.t+1<e[tx][ty]较繁琐

    初始化为INF

  2. 会存在覆盖/多次给同一个格子赋值的问题(保留最早的时间)

代码:

int m,x01,y01,t01;
int e[N][N],vis[N][N];
int nxt[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
struct node{int x,y,t;};

void bfs(int sx,int sy)
{
	int tx,ty;
	queue<node> q;
	q.push({sx,sy,0});
	vis[sx][sy]=1;
	if(e[sx][sy]==0){cout<<-1;return;}//t=0砸中(0,0)直接dead 
	if(e[sx][sy]==INF){cout<<0;return;}
	while(!q.empty()){
		node head=q.front(); q.pop();
		
		for(int i=0;i<4;++i){
			tx=head.x+nxt[i][0];
			ty=head.y+nxt[i][1];
			if(tx<0||ty<0||tx>310||ty>310) continue;
			if(!vis[tx][ty]&&head.t+1<e[tx][ty]){
				q.push({tx,ty,head.t+1});
				vis[tx][ty]=1;
				if(e[tx][ty]==INF){cout<<head.t+1;return;}
			}
		}
	}
	cout<<-1;
}

int main()
{
	int tx,ty;
	cin>>m;
	for(int i=0;i<=310;++i){
		for(int j=0;j<=310;++j){
			e[i][j]=INF;//存在t=0就砸中的情况! 
		}
	}
	for(int i=1;i<=m;++i){
		cin>>x01>>y01>>t01;
		if(e[x01][y01]==INF||e[x01][y01]>t01) e[x01][y01]=t01;//重要 
		for(int j=0;j<4;++j){
			tx=x01+nxt[j][0];
			ty=y01+nxt[j][1];
			if(tx<0||ty<0||tx>310||ty>310) continue;
			if(e[tx][ty]==INF||e[tx][ty]>t01) e[tx][ty]=t01;	
		}
	}
	bfs(0,0);
	return 0;
}

posted @ 2026-06-27 12:00  king_steph1209  阅读(4)  评论(0)    收藏  举报