记录一下错误点:判重必须立即判重,而不是等到使用的时候再判重
刚刷了一道题,一直超时,找了很久bug才找到
在BFS中,插入队列后就必须立即判重,如果在退出队列后再判重,期间会有很多次重复插入,导致超时,DFS同理
Meteor Shower
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6878 | Accepted: 2001 |
Description
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.
Input
* Line 1: A single integer: M
* Lines 2..M+1: Line i+1 contains three space-separated integers: Xi, Yi, and Ti
Output
* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.
Sample Input
4 0 0 2 2 1 2 1 1 2 0 3 5
Sample Output
5
附上AC代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define ll long long
int m;
int mapp[350][350];
int dx[] = {-1,1,0,0,0};
int dy[] = {0,0,-1,1,0};
struct M
{
int x,y,t;
}met[50005];
bool cmp(M one,M two)
{
return one.t < two.t;
}
int bfs()
{
queue<M> q;
M m;
m.x = 0;
m.y = 0;
m.t = 0;
q.push(m);
while(!q.empty())
{
M m = q.front();
q.pop();
//cout << m.x << ' '<< m.y << ' '<< m.t<<endl;
if(mapp[m.x][m.y] == -1)
return m.t;
for(int i = 0;i <= 3;i++)
{
M mm = m;
mm.x+=dx[i];
mm.y+=dy[i];
mm.t++;
if(mm.x >= 340 || mm.y >= 340 || mm.x < 0 || mm.y < 0)
continue;
else if(mapp[mm.x][mm.y] == -1 || mapp[mm.x][mm.y] > mm.t)
{
q.push(mm);
if(mapp[mm.x][mm.y] != -1)
mapp[mm.x][mm.y] = 0;//这个加入队列的时候就必须修改来判重,否则如果出队列再判重,这期间可能会再有很多次重复插入
}
}
}
return -1;
}
int main()
{
while(cin >> m)
{
memset(mapp,-1,sizeof(mapp));
for(int i = 0;i < m;i++)
scanf("%d%d%d",&met[i].x,&met[i].y,&met[i].t);
sort(met,met+m,cmp);
for(int i = 0;i < m;i++)
for(int j = 0;j <= 4;j++)
{
M temp = met[i];
temp.x+=dx[j];
temp.y+=dy[j];
if(temp.x < 0 || temp.y < 0 || temp.x >= 340 || temp.y >= 340)
continue;
else if(mapp[temp.x][temp.y] == -1)
mapp[temp.x][temp.y] = temp.t;
}
cout << bfs() <<endl;
}
//cout << "AC" <<endl;
return 0;
}