首先我们如果单单口胡,很容易想到一个 的 BFS(其中 表示牛的朝向数,本题为 )。
写的时候我们观察到这是 USACO 题,放心使用 STL,对于一个结构体我们开朝右走的奶牛坐标、朝上走的奶牛坐标、朝右走的奶牛方向。
然后我们思考怎么判重。我们发现,如果开五维数组,可能会碰到下面的问题:
- 发现结构体又要一个一个解绑,代码量上升。
- 这道题问题不大,如果是其他题,可能产生大量浪费,空间受不了。
因此我们采用 unordered_map/set 就可以很好地解决。
很多同学(包括我)之前都没有用过这玩意存自定义结构体,因为显然 STL 并不会为这种东西提供 hash_policy。因此这里简单地教一下。
首先,你需要重载 ==,因为这是 unordered,所以你并不需要重载小于号。
然后,你需要手写哈希函数。这个哈希和我们平时的哈希不同,由于哈希表大小是 STL 决定的,你并不需要求余,直接返回一个 size_t 就行了。
总而言之,你需要写下面这种东西:
struct node{int x1,y1,x2,y2,dir;};
bool operator == (node x,node y){return x.x1==y.x1 and x.x2==y.x2 and x.y1==y.y1 and x.y2==y.y2 and x.dir==y.dir;}//定义相等
struct my_hash//定义哈希
{
size_t operator () (node x)const//这句话其实可以直接背(
{
return (((x.x1*20+x.y1)*20+x.x2)*20+x.y2)*4+x.dir;
}
};
unordered_map<node,int,my_hash> dis;//在最后一个参数的位置写上你的哈希其他地方就大同小异了。下面放出参考代码:
#include<bits/stdc++.h>
using namespace std;
#define x1 eoifgjfkwdf
#define y1 poeirtwepfjdkl
const int dry[]={1,0,-1,0};
const int drx[]={0,-1,0,1};
const int duy[]={0,-1,0,1};
const int dux[]={-1,0,1,0};
int n;
char mp[22][22];
struct node{int x1,y1,x2,y2,dir;};
bool operator == (node x,node y){return x.x1==y.x1 and x.x2==y.x2 and x.y1==y.y1 and x.y2==y.y2 and x.dir==y.dir;}
struct my_hash
{
size_t operator () (node x)const
{
return (((x.x1*20+x.y1)*20+x.x2)*20+x.y2)*4+x.dir;
}
};
unordered_map<node,int,my_hash> dis;
queue<node> q;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%s",mp[i]+1);
q.push({n,1,n,1,0});
dis[{n,1,n,1,0}]=0;
while(q.size())
{
node qf=q.front();int qd=dis[qf];q.pop();
node rht={qf.x1,qf.y1,qf.x2,qf.y2,(qf.dir+1)%4};
if(dis.count(rht)==0)
q.push(rht),dis[rht]=qd+1;
node lft={qf.x1,qf.y1,qf.x2,qf.y2,(qf.dir+3)%4};
if(dis.count(lft)==0)
q.push(lft),dis[lft]=qd+1;
if(not(qf.x1==1 and qf.y1==n) and mp[qf.x1+drx[qf.dir]][qf.y1+dry[qf.dir]] == 'E')
qf.x1+=drx[qf.dir],qf.y1+=dry[qf.dir];
if(not(qf.x2==1 and qf.y2==n) and mp[qf.x2+dux[qf.dir]][qf.y2+duy[qf.dir]] == 'E')
qf.x2+=dux[qf.dir],qf.y2+=duy[qf.dir];
if(dis.count(qf)==0)
q.push(qf),dis[qf]=qd+1;
}
int ans=0x3f3f3f3f;
if(dis.count({1,n,1,n,0}))ans=min(ans,dis[{1,n,1,n,0}]);
if(dis.count({1,n,1,n,1}))ans=min(ans,dis[{1,n,1,n,1}]);
if(dis.count({1,n,1,n,2}))ans=min(ans,dis[{1,n,1,n,2}]);
if(dis.count({1,n,1,n,3}))ans=min(ans,dis[{1,n,1,n,3}]);
printf("%d\n",ans);
return 0;
}