跳到正文

题解

题解:P3610 [USACO17JAN] Cow Navigation G

PacoHelpisto约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年5月29日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟
题目
P3610

版本

  1. v1当前

很容易想到BFS
由于奶牛一开始有两个朝向,所以当成两头奶牛一起走。 开一个六维数组,每一维分别为第一头牛的x,y坐标,第二头牛的x,y坐标以及两头牛的朝向
注意! 1.左下角是(1,1) 右上角是(n,n)!!! 2.走到终点后之后的指令无效,也就是说,一头牛到了终点之后它就不会动了!

C++
#include<bits/stdc++.h>
using namespace std;
const int dx[4]={0,1,0,-1};
const int dy[4]={1,0,-1,0};
int n,vis[25][25][25][25][4][4];
struct node{
  int x1,y1,x2,y2,s1,s2,step;
  bool operator<(const node x)const{
    return x.step<step;
  }
};
priority_queue<node>q;
char mapo[25][25];
void movado(int &x,int &y,int i)
{
  if(x==1 and y==n)return ;
  x=x+dx[i],y=y+dy[i];
  if(mapo[x][y]=='H' or x<=0 or x>n or y<=0 or y>n)x-=dx[i],y-=dy[i];
}
int main()
{
  cin>>n;
  for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++)
      cin>>mapo[i][j];
  q.push({n,1,n,1,0,3,0});
  while(!q.empty())
  {
    auto[x1,y1,x2,y2,s1,s2,step]=q.top();
    q.pop();
    if(vis[x1][y1][x2][y2][s1][s2])continue;
    vis[x1][y1][x2][y2][s1][s2]=1;
    //if(step<10)cout<<x1<<' '<<y1<<' '<<x2<<' '<<y2<<' '<<step<<' '<<s1<<' '<<s2<<endl;
    if(x1==1 and y1==n and x2==1 and y2==n)
    {
      cout<<step<<endl;
      return 0;
    }
    for(int i=0;i<3;i++)
    {
      if(i==0)
      {
        int dx1=x1,dx2=x2,dy1=y1,dy2=y2;
        movado(dx1,dy1,s1);
        movado(dx2,dy2,s2);
        if(vis[dx1][dy1][dx2][dy2][s1][s2])continue;
        q.push({dx1,dy1,dx2,dy2,s1,s2,step+1});
      }
      else if(i==1)
      {
        int ds1=(s1+1)%4,ds2=(s2+1)%4;
        if(vis[x1][y1][x2][y2][ds1][ds2])continue;
        q.push({x1,y1,x2,y2,ds1,ds2,step+1});
      }
      else
      {
        int ds1=(s1-1+4)%4,ds2=(s2-1+4)%4;
        if(vis[x1][y1][x2][y2][ds1][ds2])continue;
        q.push({x1,y1,x2,y2,ds1,ds2,step+1});
      }
    }
  }
}
原文