POJ Holedox Moving BFS hash判重

这个题被stl的queue坑了2小时,一直re,换成手写的队列就ac了

#include<cstdio> #include<stdlib.h> #include<queue> #include<cstring> using namespace std; int n,m,l,k; int map[25][25]; bool visit[25][25][16400]; int h[4]={1,-1,0,0}; int g[4]={0,0,1,-1}; struct point{ int x[10],y[10]; int dir[10]; int step; }que[50010]; int front,rear; int pre_dir(int px,int py,int x,int y){//计算蛇的每一节身体相对前一节方向 if(x>px) return 0; else if(x<px) return 3; else if(y>py) return 2; else return 1; } int calhash(struct point & now){//用位运算压缩存储状态 int i,sum; sum=0; for(i=2;i<=l;i++) sum=sum*4+now.dir[i]; return sum; } int bfs(){ int i,j,xx,yy,addr; while(front !=rear){ front=(front+1)%50000; struct point tem; tem=que[front]; if(tem.x[1]==1 && tem.y[1]==1){ return tem.step; } for(i=2;i<=l;i++) map[tem.x[i]][tem.y[i]]=-1; for(i=0;i<=3;i++){ xx=tem.x[1]+h[i]; yy=tem.y[1]+g[i]; if(xx<=0 || xx>n || yy<=0 || yy>m) continue; if(map[xx][yy]==0){ struct point temp; temp.step=tem.step+1; temp.x[1]=xx; temp.y[1]=yy; temp.dir[2]=pre_dir(xx,yy,tem.x[1],tem.y[1]); for(j=2;j<=l;j++){ temp.x[j]=tem.x[j-1]; temp.y[j]=tem.y[j-1]; if(j!=2) temp.dir[j]=tem.dir[j-1]; } addr=calhash(temp); if(visit[xx][yy][addr]) continue; visit[xx][yy][addr]=true; rear=(rear+1)%50000; que[rear]=temp; } } for(i=2;i<=l;i++) map[tem.x[i]][tem.y[i]]=0; } return -1; } int main(){ int i,j,x,y,C=0,res; while(scanf("%d %d %d",&n,&m,&l)==3 && !(n==0 && m==0 && l==0)){ memset(map,0,sizeof(map)); memset(visit,0,sizeof(visit)); front=-1; rear=0; struct point sta; for(i=1;i<=l;i++){ scanf("%d %d",&sta.x[i],&sta.y[i]); if(i!=1) sta.dir[i]=pre_dir(sta.x[i-1],sta.y[i-1],sta.x[i],sta.y[i]); } sta.step=0; que[0]=sta; scanf("%d",&k); for(i=1;i<=k;i++){ scanf("%d %d",&x,&y); map[x][y]=-1; } int addr=calhash(sta); visit[sta.x[1]][sta.y[1]][addr]=true; printf("Case %d: %d\n",++C,bfs()); } }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值