HDU_1548_A strange lift
题意:一部电梯(共top层),每一楼有一个数字k,在该层只能上k层或者下k层(up和down按钮),问从当前层到目标层按按钮的最小次数。
分析:广度优先搜索。
总结:初写BFS,仿照别人的代码,这方面要继续加强。
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; int k[205],vis[205]; int top,now,aim; struct node { int floor,step;; }; bool judge(int a) { if(a>=1&&a<=top) return 1; return 0; } int BFS(node sta) { queue<node>q; node now,next; vis[sta.floor]=1; q.push(sta); while(!q.empty()) { now=q.front(); q.pop(); if(now.floor==aim) return now.step; for(int i=-1; i<=1; i+=2) { if(!vis[now.floor+i*k[now.floor]]&&judge(now.floor+i*k[now.floor])) { next.floor=now.floor+i*k[now.floor]; next.step=now.step+1; vis[now.floor+i*k[now.floor]]=1; q.push(next); } } } return -1; } int main() { while(scanf("%d",&top)!=EOF&&top) { scanf("%d%d",&now,&aim); for(int i=1; i<=top; i++) scanf("%d",&k[i]); node a; a.floor=now; a.step=0; memset(vis,0,sizeof(vis)); int ans=BFS(a); printf("%d\n",ans); } return 0; }