您的位置:首页 > 其它

HDU 1548 A strange lift

2015-08-11 16:53 363 查看

原题链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1548

题目大意:

输入N,A,B。分别表示有N层楼,最初楼层为A。终点楼层为B。然后是N个数表示在第i层楼按上或者下可以移动多少层。楼层不能超过N也不能低于1.

例如:

5 1 5

3 3 1 2 5

表示有5层楼,起点为1.终点为5。在3楼时。按下按钮可以上1层楼,或者下1层楼。

思路:

采用一般的bfs的方法既可以解得

一个数组存放访问标记是否到过这层楼。

一个数组存放到达这层楼的前一层楼是哪一层

越界判定和输出判定

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

int N,A,B;
int Floor[205];
int Check[205];
int Pre[205];
int number;
int Up_Down[2]={ 1, -1 };
bool Can;

bool bIsLeagal(int Next )
{
if( Next < 1 || Next > N )
return false;
return true;
}

void GetCount(int Index)
{
while( Pre[ Index ] != -1 )
{
Index = Pre[ Index ];
number++;
}

}
void bfs()
{
queue<int> check_floor;
memset( Check,0,sizeof(Check));
memset( Pre,0,sizeof( Pre ));
Pre[A] = -1;
Check[A] = true;
check_floor.push ( A );

int Now,Next;
while( !check_floor.empty ())
{
Now = check_floor.front ();
check_floor.pop ();
if( Now == B )
{
Can = true;
GetCount( Now );
return;
}
int i;
for( i = 0; i < 2; i++ )
{
Next = Now + Floor[Now] * Up_Down[i];
if( bIsLeagal( Next ) && !Check[Next] )
{
Pre[Next] = Now;
Check[Next] = true;
check_floor.push ( Next );
}

}
}
}
int main()
{
while( cin >> N  )
{
if( N == 0 ) break;
cin >> A >> B;
Can = false;
number = 0;
memset( Floor,0,sizeof( Floor));
int i;
for( i = 1; i <= N; i++ )
cin>> Floor[i];
bfs();
if( Can )
cout<< number <<endl;
else
cout<<-1<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs 搜索