第一个成员开始正好走到数组最后一个成员所使用的最小步骤数(三种方法)
import java.util.*; public class Main {
static int min = Integer.MAX_VALUE;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNextInt()){
int n = Integer.parseInt(in.next());
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = in.nextInt();
}
System.out.println(df(arr, 0, 0) +" " + dp(arr, 0) + " " + dt(arr));
}
}
public static int df(int[] arr, int i, int k){
if(arr.length <= 2) return 1;
if(i == arr.length - 1) return k;
if(i >= arr.length) return -1;
if(i == 0){
int min = arr.length;
for(int j=1; j<arr.length/2; j++){
int t = df(arr, i+j, k+1);
if(t>0){
min = Math.min(min, t);
}
}
return min==arr.length?-1:min;
}
return df(arr, i+arr[i], k+1);
}
public static int dp(int[] arr, int i){
if(arr.length <= 2) return 1;
if(i == arr.length - 1) return 0;
if(i >= arr.length) return -1;
int res = arr.length;
if(i == 0){
for(int j=1; j<arr.length/2; j++){
int t = dp(arr, i+j);
if(t > 0){
res = Math.min(res, t);
}
}
res = res==arr.length?-1:res+1;
} else {
int t = dp(arr, i+arr[i]);
res = t<0?-1:t+1;
}
return res;
}
public static int dt(int[] arr){
if(arr.length <= 2) return 1;
int[] dt = new int[arr.length];
dt[0] = 0;
dt[1] = 1;
for(int i=2; i<arr.length; i++){
if(i<arr.length/2){
dt[i] = 1;
} else{
dt[i] = i+1;
for(int j=1; j<i; j++){
if(dt[j] < 0) continue;
int count = 1;
int index = j;
while(index < i){
index += arr[index];
count++;
}
if(index == i){
dt[i] = Math.min(dt[i], count);
}
}
if(dt[i] > i) dt[i] = -1;
}
}
return dt[arr.length-1];
}
}