BZOJ 1644: [Usaco2007 Oct]Obstacle Course 障碍训练课【SPFA】

1644: [Usaco2007 Oct]Obstacle Course 障碍训练课

题目描述
传送门

题解

SPFA一下就好了,dst[f][x][y]表示在(x,y)这个位置方向为f的最优解。

代码如下

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int flg[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int n,sx,sy,ex,ey,dst[4][105][105],INF;
bool vis[4][105][105];
char mp[105][105];
struct xcw{int x,y,f;};
queue<xcw> que;
bool check(int x,int y){
    if(x<1||x>n||y<1||y>n) return 0;
    return mp[x][y]=='.';
}
int BFS(int x,int y){
    memset(dst,63,sizeof(dst));INF=dst[0][0][0];
    for(int i=0;i<4;i++) que.push((xcw){x,y,i}),vis[i][x][y]=1,dst[i][x][y]=0;
    while(!que.empty()){
        x=que.front().x,y=que.front().y;int f=que.front().f;que.pop();
        vis[f][x][y]=0;
        for(int i=0;i<4;i++){
            int xx=x+flg[i][0],yy=y+flg[i][1];
            if(!check(xx,yy)) continue;
            if(dst[i][xx][yy]>dst[f][x][y]+(f!=i)){
                dst[i][xx][yy]=dst[f][x][y]+(f!=i);
                if(!vis[i][xx][yy]) vis[i][xx][yy]=1,que.push((xcw){xx,yy,i});
            }
        }
    }
    int Ans=INF;
    for(int i=0;i<4;i++) Ans=min(Ans,dst[i][ex][ey]);
    return Ans;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("prob.in","r",stdin);
    freopen("prob.out","w",stdout);
    #endif
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%s",mp[i]+1);
        for(int j=1;j<=n;j++){
            if(mp[i][j]=='A') sx=i,sy=j,mp[i][j]='.';
            if(mp[i][j]=='B') ex=i,ey=j,mp[i][j]='.';
        }
    }
    while(!que.empty()) que.pop();
    printf("%d\n",BFS(sx,sy));
    return 0;
}
posted @ 2018-06-07 21:53  XSamsara  阅读(135)  评论(0编辑  收藏  举报