标签:static out sub 数组 break while integer puts -o
输入分两行,第一行是数组长度N (1 ≤ N ≤ 10000),第二行是每一项的值,用空格分隔。
输出最少的跳数,无法到达输出-1
5 2 0 1 1 1
4
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 4 public class Main { 5 6 public static void main(String[] args) throws Exception{ 7 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 String str; 9 String[] strs; 10 int n; 11 12 while((str = br.readLine()) != null){ 13 n = Integer.parseInt(str.trim()); 14 str = br.readLine(); 15 strs = str.trim().split(" "); 16 int[] input = new int[n]; 17 for(int i = 0; i < n; ++i) 18 input[i] = Integer.parseInt(strs[i]); 19 int step = 1; 20 int now = input[0]; 21 int next = now; 22 for(int i = 1; i < n; ++i){ 23 if(i == now){ 24 next = Math.max(next, i + input[i]); 25 if(next == now){ 26 System.out.println(-1); 27 break; 28 } 29 ++step; 30 now = next; 31 if(next >= n){ 32 System.out.println(step); 33 break; 34 } 35 } 36 else{ 37 next = Math.max(next, i + input[i]); 38 if(next >= n){ 39 System.out.println(++step); 40 break; 41 } 42 } 43 } 44 } 45 } 46 }
标签:static out sub 数组 break while integer puts -o
原文地址:https://www.cnblogs.com/4545mdf/p/9108150.html