搜索練習1
P2895 [USACO08FEB]流星雨Meteor Shower
題目描述
Bessie hears that an extraordinary meteor shower is coming; reports say that these meteors will crash into earth and destroy anything they hit. Anxious for her safety, she vows to find her way to a safe location (one that is never destroyed by a meteor) . She is currently grazing at the origin in the coordinate plane and wants to move to a new, safer location while avoiding being destroyed by meteors along her way.
The reports say that M meteors (1 ≤ M ≤ 50,000) will strike, with meteor i will striking point (Xi, Yi) (0 ≤ Xi ≤ 300; 0 ≤ Yi ≤ 300) at time Ti (0 ≤ Ti ≤ 1,000). Each meteor destroys the point that it strikes and also the four rectilinearly adjacent lattice points.
Bessie leaves the origin at time 0 and can travel in the first quadrant and parallel to the axes at the rate of one distance unit per second to any of the (often 4) adjacent rectilinear points that are not yet destroyed by a meteor. She cannot be located on a point at any time greater than or equal to the time it is destroyed).
Determine the minimum time it takes Bessie to get to a safe place.
牛去看流星雨,不料流星掉下來會砸毀上下左右中五個點。每個流星掉下的位置和時間都不同,求牛能否活命,如果能活命,最短的逃跑時間是多少?
輸入輸出格式
輸入格式:
-
Line 1: A single integer: M
- Lines 2..M+1: Line i+1 contains three space-separated integers: Xi, Yi, and Ti
輸出格式:
- Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.
輸入輸出出樣例
輸入樣例#1: 復制4 0 0 2 2 1 2 1 1 2 0 3 5輸出樣例#1: 復制
5
solution:
預處理所有位置被砸毀的時間(最早砸毀時間)
bfs直接搜索到達一個不會被砸毀的位置的最短時間(最小步數就是最短時間,因為每秒鐘走1步)
需要註意如果你到達某個位置的時間是晚於it被砸毀的時間的,那麽這個位置是無效的
Code:
#include<queue> #include<cstdio> #include<cstring> #include<iostream> using namespace std; const int M = 50010; const int N = 506; int m,map[400][400],vis[400][400]; struct Node { int x,y,t; } star[M]; queue<Node>que; int dx[4]= {0,0,-1,1}, dy[4]={-1,1,0,0}; int bfs() { if(map[0][0]==-1) return 0; //初始位置沒被砸毀 if(map[0][0]==0) return -1; //初始位置在最開始就被砸毀 Node s; s.x=0,s.y=0,s.t=0; que.push(s); vis[0][0]=1; while(!que.empty()) { Node tmp=que.front(); que.pop(); for(int i=0; i<4; i++) { Node tmp2; tmp2.x=tmp.x+dx[i]; tmp2.y=tmp.y+dy[i]; tmp2.t=tmp.t+1; if(tmp2.x<0 || tmp2.x>=N || tmp2.y<0 || tmp2.y>=N) continue;//越界 if(map[tmp2.x][tmp2.y]==-1) return tmp2.t; //如果搜索點沒被砸毀,那麽直接返回這個時間,就是最短步數 if(tmp2.t>=map[tmp2.x][tmp2.y]) continue; //如果搜索點的時間比該位置被砸毀的時間大,這個點無貢獻 if(tmp2.x>=0 && tmp2.x<N && tmp2.y>=0 &&tmp2.y<N) { if(!vis[tmp2.x][tmp2.y]) { //沒搜過繼續搜 que.push(tmp2); vis[tmp2.x][tmp2.y]=1; } else continue; } } } return -1; } int main() { memset(map,-1,sizeof(map)); memset(vis,0,sizeof(vis)); scanf("%d",&m); for(int i=1; i<=m; i++) { //處理每個位置被砸毀的最小時間 int x,y,t; scanf("%d%d%d",&x,&y,&t); if(map[x][y]==-1) map[x][y]=t; else map[x][y]=min(map[x][y],t); for(int j=0; j<4; j++) { int xx=x+dx[j],yy=y+dy[j]; if(xx<0 || yy<0 || xx>=N || yy>=N) continue; if(map[xx][yy]==-1) map[xx][yy]=t; else map[xx][yy]=min(map[xx][yy],t); } } cout<<bfs(); return 0; }AC
自己選的路,跪著也要走完!!!
搜索練習1