题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1548
题意:有一个建筑有N层,里面有一架电梯。给你一个起点层数和一个终点层数。在每一层都有一个按钮,按钮上面有一个数字,表示可以上或者下Ki层。然后你可以由起点开始选择上或者下(重复……),当你到达终点为止(或者不可能到达终点为止)。求你需要按按钮的次数,不能到达则输出-1。
思路:可以用BFS或是最短路
广搜:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;
int N, A, B;
int a[300];
bool map[300], flag;
struct node
{
int x, step;
} n1, n2, m;
void bfs()
{
queue <node> Q;
Q.push(n1);
map[n1.x] = true;
while(!Q.empty())
{
m = Q.front();
Q.pop();
if(m.x == B)
{
flag = true;
break;
}
n1.x = m.x - a[m.x];
n2.x = m.x + a[m.x];
if(n1.x > 0 && n1.x <= B && !map[n1.x]) //下去
{
n1.step = m.step + 1;
map[n1.x] = true;
Q.push(n1);
}
if(n2.x > 0 && n2.x <= B && !map[n2.x]) //上去
{
n2.step = m.step + 1;
map[n2.x] = true;
Q.push(n2);
}
}
if(flag)
printf("%d\n", m.step);
else
printf("-1\n");
}
int main()
{
int i;
while(~scanf("%d", &N) && N)
{
scanf("%d %d", &A, &B);
memset(map, 0, sizeof(map));
for(i = 1; i <= N; i++)
scanf("%d", &a[i]);
flag = false;
n1.x = A;
n1.step = 0;
bfs();
}
return 0;
}
最短路的话用floyd貌似超时,可以用dijkstra实现