這個題可以用搜索做,因為是求最短時間,搜索則直接想到廣搜(BFS)。
問題:首先告訴你有n層樓,要你求從第A層樓到第B層樓的最短時間。
限制及條件:
1、每層樓只能按上或者下,而且上或者下的樓層數是不同的,需要輸入的。
2、上下樓不能到達不存在的樓層(小於1樓或者大於n樓)。
3、1<=n,A,B<=200
AC代碼:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct Node
{
int f;
int i;
};
int floor[210];
int yn[210];
int Bfs(int n, int a, int b)
{
Node now,next;
queue<Node> q;
now.f = a;
now.i = 0;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
yn[now.f] = 2; //標記此樓已經到達
// printf("%d %d\n",now.f,now.i);
if(now.f == b) //判斷是否到達指定樓層
{
return now.i;
}
else
{
next.i = now.i+1;
next.f = now.f+floor[now.f]; //向上走
if(next.f > 0 && next.f <= 200 && yn[next.f] == 0)
{
yn[next.f] = 1; //標記此樓
q.push(next);
}
next.f = now.f-floor[now.f]; //向下走
if(next.f > 0 && next.f <= 200 && yn[next.f] == 0)
{
yn[next.f] = 1; //標記此樓
q.push(next);
}
}
}
return -1;
}
int main()
{
int n,a,b;
int i,num;
while(scanf("%d",&n)&&n)
{
memset(yn,0,sizeof(yn));
for(i = 0; i< 210; i++)
{
floor[i] = 1000;
}
scanf("%d%d",&a,&b);
for(i = 1; i <= n; i++)
{
scanf("%d",&floor[i]);
}
num = Bfs(n,a,b);
printf("%d\n",num);
}
return 0;
}