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

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

题目描述
传送门

题解

SPFA一下就好了, dst[f][x][y] d s t [ f ] [ x ] [ y ] 表示在 (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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值