一只袋鼠要从河这边跳到河对岸,河很宽,但是河中间打了很多柱子,略去。
这道题做完感觉也是原题,上周leetcode周赛的frog jump,前面还有几道jump的题,可以在leetcode上面搜索关键字jump。
frog jump题解链接http://www.cnblogs.com/y119777/p/5882697.html
这道题想清楚是一次只能跳这么多,还是可以这个区间随便跳,然后思路就很清楚。
1 #include<bits/stdc++.h> 2 #define pb push_back 3 #define FOR(i, n) for (int i = 0; i < (int)n; ++i) 4 #define dbg(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl 5 typedef long long ll; 6 using namespace std; 7 typedef pair<int, int> pii; 8 const int maxn = 1e3 + 10; 9 void solve() { 10 int n; 11 cin >> n; 12 vector<int> a(n + 1, 0), cnt(n + 1, -1); 13 for (int i = 0; i < n; i++) cin >> a[i]; 14 int cur = 0; 15 int step = 0; 16 int left, right; 17 left = right = 0; 18 while(1) { 19 int r = right; 20 for (int i = left; i <= right; i++) { 21 r = max(r, i + a[i]); 22 } 23 left = right + 1, right = r; 24 step ++; 25 if(left <= right && right >= n) { 26 cout << step << endl; return; 27 } 28 if(right < left) { 29 cout << -1 << endl; return; 30 } 31 } 32 33 } 34 int main() { 35 //freopen("test.in", "r", stdin); 36 //freopen("test.out", "w", stdout); 37 solve(); 38 return 0; 39 }