Total Submission(s): 8236 Accepted Submission(s): 3129
Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button "UP" or "DOWN"?
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,....kn.
A single 0 indicate the end of the input.
5 1 5 3 3 1 2 5 0
3
解题思路:这是一道比较明显的广度优先搜索题目,最少次数。和一般的广搜不同的是,化二维为一位,也因此简化了解题过程。
解题时,直接从2个方向搜索即可,没有刁难的地方。只有一点,与平常思维不同:电梯只能按上下键,不同的楼层得到的变化情况也不尽相同,这里一定要打破常规思维,严格按题目做题,不然,就一边纠结去吧!
#include<cstdio> #include<cstring> #include<queue> using namespace std; int map[200]; //电梯能运行的情况 层数 int flood[200]; //电梯停靠情况 是否停靠过,0,1 int dir[2]={1,-1}; // 电梯运行方向,向上,向下 int n,s,e; struct node { int x; int step; }; int bfs() { node now,next; queue<node> q; now.x=s; now.step=0; flood[s]=1; if(e==s) return 0; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); for(int i=0;i<2;i++) //向上或向下运行 { next.x=now.x+dir[i]*map[now.x]; next.step=now.step+1; if(next.x>=0&&next.x<n&&!flood[next.x]) //该层可停靠 { if(next.x==e) //到达目的层 return next.step; flood[next.x]=1; q.push(next); } } } return -1; } int main() { int i; while(scanf("%d",&n)&&n) { scanf("%d%d",&s,&e); s--; //数据与数据结构存储统一 e--; memset(flood,0,sizeof(flood)); for(i=0;i<n;i++) scanf("%d",&map[i]); printf("%d\n",bfs()); } return 0; }