洛谷P1135 奇怪的电梯
题目
P1135 奇怪的电梯
题目背景
感谢 @yummy 提供的一些数据。
题目描述
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 $i$ 层楼($1 \le i \le N$)上有一个数字 $K_i$($0 \le K_i \le N$)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如: $3, 3, 1, 2, 5$ 代表了 $K_i$($K_1=3$,$K_2=3$,……),从 $1$ 楼开始。在 $1$ 楼,按“上”可以到 $4$ 楼,按“下”是不起作用的,因为没有 $-2$ 楼。那么,从 $A$ 楼到 $B$ 楼至少要按几次按钮呢?
输入格式
共二行。
第一行为三个用空格隔开的正整数,表示 $N, A, B$($1 \le N \le 200$,$1 \le A, B \le N$)。
第二行为 $N$ 个用空格隔开的非负整数,表示 $K_i$。
输出格式
一行,即最少按键次数,若无法到达,则输出 -1。
输入输出样例 #1
输入 #1
5 1 5
3 3 1 2 5
输出 #1
3
说明/提示
对于 $100 %$ 的数据,$1 \le N \le 200$,$1 \le A, B \le N$,$0 \le K_i \le N$。
本题共 $16$ 个测试点,前 $15$ 个每个测试点 $6$ 分,最后一个测试点 $10$ 分。
我们根据题目意思可以得出Ki实际上就是对应i楼层可以跳跃的层数,根据具体数值大小分析上下跳跃的可行性
首先定义一个结构体方便我们待会记录队列的信息
点击查看代码
typedef struct {
int floor,count; // 楼层编号和到达该楼层所需步数
} Node;
Node queue[MAXN];
然后考虑上下两种跳跃,找出最短路径
点击查看代码
int jump = e[floor - 1]; //对应楼层的跳跃值索引
// 尝试向上
int up = floor + jump;
if (up <= N && !visited[up]) {
queue[rear].floor = up;
queue[rear].count = count + 1;
rear++;
visited[up] = 1;
}
// 尝试向下
int down = floor - jump;
if (down >= 1 && !visited[down]) {
queue[rear].floor = down;
queue[rear].count = count + 1;
rear++;
visited[down] = 1;
完整代码如下
点击查看代码
#include <stdio.h>
#include <string.h>
#define MAXN 410 //因为每个楼层都有两个方向
typedef struct {
int floor,count;
} Node;
int N, A, B;
int e[MAXN];
int visited[MAXN];
int step[MAXN];
Node queue[MAXN];
int BFS_e(){
int front = 0, rear = 0;
memset(visited, 0, sizeof(visited));
memset(step, -1,sizeof(step));
queue[rear].floor = A;
queue[rear].count = 0;
rear++;
visited[A] = 1;
while(front < rear){
Node now = queue[front++];
int floor = now.floor;
int count = now.count;
if (floor == B)
return count;
int jump = e[floor - 1]; //对应楼层的跳跃值索引
// 尝试向上
int up = floor + jump;
if (up <= N && !visited[up]) {
queue[rear].floor = up;
queue[rear].count = count + 1;
rear++;
visited[up] = 1;
}
// 尝试向下
int down = floor - jump;
if (down >= 1 && !visited[down]) {
queue[rear].floor = down;
queue[rear].count = count + 1;
rear++;
visited[down] = 1;
}
}
return -1;
}
int main(){
scanf("%d %d %d", &N, &A, &B);
for (int i = 0; i < N; i++) {
scanf("%d", &e[i]);
}
int result = BFS_e();
printf("%d\n", result);
return 0;
}

浙公网安备 33010602011771号