请教各位大佬为什么用bfs还要对结果求min才能输出正确答案? T^T
查看原帖
请教各位大佬为什么用bfs还要对结果求min才能输出正确答案? T^T
257348
theHermit楼主2020/8/22 22:03

之前做其他题也出现过这种情况,

不清楚代码中哪出了问题。

记得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;
}

2020/8/22 22:03
加载中...