第一步是选择(1,len/2)任意一步,其他的则是固定为数组上的值,值是多少就走多少步且不能多不能少. 利用for枚举第一步i=(1,len/2)然后后续步数则对于每个i模拟走下去看能否刚好到达终点,取所有能到达终点的步数的最小值即可
#include <bits/stdc++.h>
using namespace std;
#define N 100005
int n=1;
int a[N];
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
while(cin>>a[n]){
n++;
}
n--;
int ans=101;
for(int i=1;i<=n/2;i++){
int j=i;
int res=1;
while(j<n){
res++;
j+=a[j];
}
if(j==n){
ans=min(res,ans);
}
}
if(ans==101){
cout<<-1<<'\n';
}
else{
cout<<ans<<'\n';
}
return 0;
}
import sys
a = [0] # 使用 a[1] 开始存储
n = 1
# 读取输入,直到 EOF
for line in sys.stdin:
for num in map(int, line.split()):
a.append(num)
n += 1
n -= 1 # 调整 n 的值
ans = 101
# 计算答案
for i in range(1, n // 2 + 1):
j = i
res = 1
while j < n:
res += 1
j += a[j]
if j == n:
ans = min(res, ans)
# 输出结果
if ans == 101:
print(-1)
else:
print(ans)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> a = new ArrayList<>();
a.add(0); // 使用 a[1] 开始存储
int n = 1;
// 读取输入,直到没有更多数据
while (sc.hasNextInt()) {
a.add(sc.nextInt());
n++;
}
n--; // 调整 n 的值
int ans = 101;
// 计算答案
for (int i = 1; i <= n / 2; i++) {
int j = i;
int res = 1;
while (j < n) {
res++;
j += a.get(j);
}
if (j == n) {
ans = Math.min(ans, res);
}
}
// 输出结果
if (ans == 101) {
System.out.println(-1);
} else {
System.out.println(ans);
}
sc.close();
}
}
给定一个正整数数组,设为nums,最大为100个成员,求从第一个成员开始,正好走到数组最后一个成员,所使用的最少步骤数。
要求:
由正整数组成的数组,以空格分隔,数组长度小于100,请自行解析数据数量。
正整数,表示最少的步数,如果不存在输出−1
输入
7 5 9 4 2 6 8 3 5 4 3 9
输出
2
说明
第一步: 第一个可选步长选择2,从第一个成员7开始走2步,到达9;
第二步: 从9开始,经过自身数字9对应的9个成员到最后。
输入
1 2 3 7 1 5 9 3 2 1
输出
-1