2011-12-31 18:44:21
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1548
题意:有一个奇怪的电梯,只有2个按钮,上和下。第i楼层有一个值Ki。假设在第i层,按上它会向上走Ki层,按下也一样。如果超过n层或少于1层,则原地不动。问从第a层到b层需要几次操作。
mark:BFS之。
代码:
# include <stdio.h>
# include <string.h>
int aa, bb, n ;
int k[210] ;
int q[210] ;
int step[210] ;
void bfs()
{
int a, front = 0, rear =1 ;
memset (step, -1, sizeof(step)) ;
q[0] = aa ;
step[aa] = 0 ;
while (front != rear)
{
a = q[front++] ;
if (a == bb) return ;
if (a+k[a] <= n && step[a+k[a]] == -1)
{
step[a+k[a]] = step[a]+1 ;
q[rear++] = a+k[a] ;
}
if (a-k[a] >= 1 && step[a-k[a]] == -1)
{
step[a-k[a]] = step[a]+1 ;
q[rear++] = a-k[a] ;
}
}
}
int main ()
{
int i ;
while (~scanf ("%d", &n),n)
{
scanf ("%d%d", &aa, &bb) ;
for (i = 1 ; i <= n ; i++)
scanf ("%d", &k[i]) ;
bfs() ;
printf ("%d\n", step[bb]) ;
}
return 0 ;
}