USACO 2.4.2 穿越栅栏 Overfencing

博客介绍了USACO竞赛中关于穿越栅栏(Overfencing)的问题,指出虽然题目简单,但因繁复的迷宫图数据导致解题过程需要耐心和细心。博主提出了解决方案,采用BFS广度优先搜索算法,并强调需要进行两次搜索以获取最短步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题解

此题不难,但是很恶心。迷宫的图数据太繁琐了,比较考验细心。
做法就是单纯的BFS,判断后加步数就好。但是要走两次,然后每处取最小,最后判断即可。


Code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <utility>
#include <algorithm>
using namespace std;
int n,m;

typedef pair<int,int> P;
int cot[250][80];
int step[250][80];
int step_ct[5000];
int Mx[4]={-2,0,2,0};
int My[4]={0,2,0,-2};

int exo[2][2];

void bfs(int i,int j){
    queue<P> que;
    que.push( P(i,j));
    step[i][j] = 1;
    P tmp;
    int tmpx,tmpy;
    while( !que.empty()){
        tmp = que.front();
        que.pop();

        for(int k=0;k<4;k++){
            tmpx = tmp.first + Mx[k]/2;
            tmpy = tmp.second + My[k]/2;

            if(cot[tmpx][tmpy]==1) continue;

            tmpx = tmp.first + Mx[k];
            tmpy = tmp.second + My[k];

            if( tmpx>0 && tmpx<2*n &&
                tmpy>0 && tmpy<2*m && step[tmpx][tmpy]==0 &&
            cot[tmpx][tmpy]!=1) {
                step[tmpx][tmpy] = step[tmp.first][tmp.second]+1;
                que.push(P(tmpx,tmpy));
            }
        }
    }
}
int main(void){

    freopen("maze1.out","w",stdout);
    freopen("maze1.in","r",stdin);

    cin>>m>>n;
    string str;
    getchar();// 神烦
    for(int i=0;i<2*n+1;i++){
        getline(cin,str);
        for(int j=0;j<2*m+1;j++){
            if(str[j]=='-'||str[j]=='+'||str[j]=='|') cot[i][j] = 1;
        }
    }

    int t=0,ex; // exo 出口
    for(int i=0;i<=2*n;i+=2*n)
        for(int j=0;j<2*m+1;j++)
            if(cot[i][j] == 0){
                if(i==0) ex=1;// 用ex处理一下 使得计算时候在迷宫内
                else ex=-1;
                exo[t][0]=i+ex;
                exo[t++][1]=j;
            }
    for(int j=0;j<=2*m;j+=2*m)
        for(int i=0;i<2*n+1;i++)
            if(cot[i][j] == 0){
                if(j==0) ex=1;
                else ex=-1;
                exo[t][0]=i;
                exo[t++][1]=j+ex;
            }

    bfs(exo[0][0],exo[0][1]);// 第一次

    int k=0;
    for(int i=0;i<2*n+1;i++)
        for(int j=0;j<2*m+1;j++){
            if(step[i][j]!=0) step_ct[k++]=step[i][j];// 步数记录集合
        }
    memset(step,0,sizeof(step));

    bfs(exo[1][0],exo[1][1]);// 第二次

    k=0;
    for(int i=0;i<2*n+1;i++)
        for(int j=0;j<2*m+1;j++){
            if(step[i][j]!=0) {
                step_ct[k]=min(step_ct[k],step[i][j]);// 步数记录集合 更新
                k++;
            }
        }
    int ans = 0;
    for(int i=0;i<k;i++){
        ans = max(step_ct[i],ans);
    }
    cout<<ans<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值