theHermit @ 2020-08-22 22:03:33
之前做其他题也出现过这种情况,
不清楚代码中哪出了问题。
记得bfs第一个解就是最优解啊...
不明白哪出了问题
蒟蒻跪求各位大佬指正!
#include<bits/stdc++.h>
#define For(i,m,n) for(int i=m;i<n;i++)
//#define rFor(i,n,m) for(int i=n;i>m;i--)
#define r(a) read(a)
#define rr(a,b) read(a),read(b)
#define rrr(a,b,c) read(a),read(b),read(c)
using namespace std;
typedef long long ll;
typedef unsigned long long Ull;
template <class T>
void read(T &x){
T f=1;
x=0;
char ch=getchar();
while(ch=='\n'){ch=getchar();}
while(ch<'0'||ch>'9') if(ch=='-'){f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') {x=(x<<1)+(x<<3)+(ch-'0');ch=getchar();}
x*=f;
}
struct state{
int x;
int y;
int t;
};
const int MAX=1e5;
int t[MAX];
const int INF=1e7;
const int BOUND=303;
int mp[BOUND][BOUND];
bool vis[BOUND][BOUND];
state startPos;
int n;
Ull a,b,c;
Ull have;
int res=INF;
state mov[5]={{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,0}};
bool IsSafe(state next)
{
return !vis[next.x][next.y]&&next.t<mp[next.x][next.y]&&next.x>-1&&next.y<BOUND&&next.x<BOUND&&next.y>-1;
}
void heatMp(state now)
{
For(i,0,5){
state next;
next.x=mov[i].x+now.x;
next.y=mov[i].y+now.y;
next.t=now.t;
if(IsSafe(next))
mp[next.x][next.y]=min(next.t,mp[next.x][next.y]);
}
}
void input_1()
{
r(n);
For(i,0,BOUND){
For(j,0,BOUND){
mp[i][j]=INF;
}
}
For(i,0,n){
state tmpPos;
rrr(tmpPos.x,tmpPos.y,tmpPos.t);
heatMp(tmpPos);
}
startPos.t=startPos.x=startPos.y=0;
}
bool IsEnd(state now)
{
return mp[now.x][now.y]==INF;
}
void bfs(state startPos)
{
queue<state> Q;
Q.push(startPos);
while(Q.size()){
state now=Q.front();
Q.pop();
For(i,0,4){
state next;
next.x=mov[i].x+now.x;
next.y=mov[i].y+now.y;
next.t=now.t+1;
if(IsSafe(next)){
if(IsEnd(next)){
res=next.t;
break;
// res=min(next.t,res);
//此处res和break换成注释部分就能AC
// continue;
}
Q.push(next);
vis[next.x][next.y]=1;
}
}
}
if(res==INF) res=-1;
}
void show()
{
cout<<res;
}
int main()
{
input_1();
vis[0][0]=1;
bfs(startPos);
show();
return 0;
}
by theHermit @ 2020-08-22 22:06:11
快哭了,救救孩子吧!!!
by haooo @ 2020-08-22 22:25:03
DJ是第一次出队一定是最优
by haooo @ 2020-08-22 22:26:07
而且那是dj,是优先队列优化过的bfs
by haooo @ 2020-08-22 22:29:46
@theHermit
by theHermit @ 2020-08-22 22:33:02
@haooo 谢谢大佬的回复!~ 算法萌新不懂就问,Dj是Dijkstra最短路吗
by haooo @ 2020-08-22 22:42:33
对
by theHermit @ 2020-08-23 08:32:31
@haooo
谢谢大佬!
by haooo @ 2020-08-23 23:39:38
@theHermit 啊这,突然发现那有一点不对。
貌似在这道题中,bfs第一次取出的一定就是最优的了。
by haooo @ 2020-08-23 23:40:42
我太弱了。。
by theHermit @ 2020-08-24 08:33:40
@haooo
啊...可是我放在开头的代码就是取第一次的呀
可是它会WA五个点啊..