首页 > 代码库 > CDZSC_2015寒假新人(4)——搜索 C
CDZSC_2015寒假新人(4)——搜索 C
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button "UP" , you will go up Ki floor,i.e,you will go to the i+Ki th floor,as the same, if you press the button "DOWN" , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can‘t go up high than N,and can‘t go down lower than 1. For example, there is a buliding with 5 floors, and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button "UP", and you‘ll go up to the 4 th floor,and if you press the button "DOWN", the lift can‘t do it, because it can‘t go down to the -2 th floor,as you know ,the -2 th floor isn‘t exist.
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"?
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"?
Input
The input consists of several test cases.,Each test case contains two lines.
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.
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.
Output
For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can‘t reach floor B,printf "-1".
Sample Input
5 1 5
3 3 12 5
0
Sample Output
3
思路:bfs,有2个搜索方向,如果up就i(现在的楼层)+ki ,down就i-ki。
PS有个地方要注意ab相同时输出0.
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 using namespace std; 6 int vis[210],le[210],n; 7 int bfs(int a,int b) 8 { 9 int c;10 memset(vis,0,sizeof(vis));11 queue<int>q;12 q.push(a);13 while(!q.empty())14 {15 c=q.front();16 q.pop();17 if(c+le[c]<=n&&!vis[c+le[c]])18 {19 vis[c+le[c]]=vis[c]+1;20 q.push(c+le[c]);21 }22 if(c-le[c]>=1&&!vis[c-le[c]])23 {24 vis[c-le[c]]=vis[c]+1;25 q.push(c-le[c]);26 }27 }28 if(vis[b]!=0)29 {30 return vis[b];31 }32 else33 {34 return -1;35 }36 }37 int main()38 {39 #ifdef CDZSC_OFFLINE40 freopen("in.txt","r",stdin);41 #endif42 int i,a,b,sum;43 while(scanf("%d",&n)&&n!=0)44 {45 scanf("%d%d",&a,&b);46 for(i=1; i<=n; i++)47 {48 scanf("%d",&le[i]);49 }50 if(a==b)//相同时输出051 {52 printf("0\n");53 continue;54 }55 sum=bfs(a,b);56 printf("%d\n",sum);57 }58 return 0;59 }
CDZSC_2015寒假新人(4)——搜索 C
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。