Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2783176
  • 博文数量: 471
  • 博客积分: 7081
  • 博客等级: 少将
  • 技术积分: 5369
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-04 21:55
文章分类

全部博文(471)

文章存档

2014年(90)

2013年(69)

2012年(312)

分类: C/C++

2012-04-17 11:21:14

这题是最简单最纯粹的bfs广搜,只要作一下标记去过的地方,不能再去,就OK啦! 
链接:
when you is on floor A,and you want to go to floor B,how many times at least he havt to
press the button "UP" or "DOWN"?
题意:一个特别的电梯,按up可升上k[i]层,到大i+k[i]层,down则到达i-k[i]层,最高不能超过n
,最低不能小于1,给你一个起点和终点,问最少可以按几次到达目的地。
在一个N层高的楼有一个奇怪的电梯,在每一层只能上升或下降一个特定的层数,中间不会停止,在
给定的条件下,问能不能到达指定楼层,可以到达的话返回转操作次数,不可以的话返回-1.
 
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.
 
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".
 
N A B
Sample Input
5 1 5
3 3 1 2 5
0
 
Sample Output
3
 
充分利用flag[]数组来标记,所走过的步数

点击(此处)折叠或打开

  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;

  4. int N,A,B;
  5. int floor[255],flag[255];

  6. void BFS(int S,int E)
  7. {
  8.     
  9.     queue<int>q;
  10.     q.push(S);
  11.     flag[S]=1;//先将它初始化
  12.     int t;//可能会没有解,所以不在里面声明
  13.     while(!q.empty())
  14.     {
  15.         t=q.front();
  16.     
  17.         q.pop();//取得队头元素之后,马上出队
  18.         if(t==E)
  19.             break;//匹配成功
  20.         int next=t+floor[t];//i,ki
  21.     
  22.         if(next>=1 && next<=B && flag[next]==0)//向上
  23.         {
  24.             q.push(next);
  25.             flag[next]=flag[t]+1;
  26.             //printf("%d",next);
  27.         }

  28.         next=t-floor[t];//i,ki
  29.         if(next>=1 && next<=B && flag[next]==0)//向下
  30.         {
  31.             q.push(next);
  32.             flag[next]=flag[t]+1;
  33.             //printf("%d",next);
  34.         }

  35.     }
  36.     if(t!=E)
  37.         flag[B]=0;//匹配不成功
  38. }
  39. int main()
  40. {
  41.     while(scanf("%d",&N)&& N!=0)
  42.     {
  43.         scanf("%d %d",&A,&B);
  44.             for(int i=1;i<=N;i++)
  45.             {
  46.                 scanf("%d",&floor[i]);
  47.             }
  48.             memset(flag,0,sizeof(flag));
  49.         BFS(A,B);
  50.         printf("%d\n",flag[B]-1);//因为一开始将flag[A]=1
  51.     }
  52.     return 0;
  53. }

阅读(3798) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~