【题解】Long Jumps 【水题】
链接:https://codeforces.com/contest/1472/problem/C
C. Long Jumps
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it:
- At first, choose index i(1≤i≤n) — starting position in the array. Put the chip at the index i (on the value ai).
- While i≤n, add aiai to your score and move the chip aiai positions to the right (i.e. replace i with i+ai).
- If i>n, then Polycarp ends the game.
For example, if n=5 and a=[7,3,1,2,3], then the following game options are possible:
- Polycarp chooses i=1. Game process: i=1⟶+78. The score of the game is: a1=7.
- Polycarp chooses i=2. Game process: i=2⟶+35⟶+38. The score of the game is: a2+a5=6.
- Polycarp chooses i=3. Game process: i=3⟶+14⟶+26. The score of the game is: a3+a4=3.
- Polycarp chooses i=4. Game process: i=4⟶+26. The score of the game is: a4=2.
- Polycarp chooses i=5. Game process: i=5⟶+38. The score of the game is: a5=3.
Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.
Input
The first line contains one integer t(1≤t≤1e4) — the number of test cases. Then tt test cases follow.
The first line of each test case contains one integer n (1≤n≤2e5) — the length of the array aa.
The next line contains nn integers a1,a2,…,an (1≤ai≤1e9) — elements of the array a.
It is guaranteed that the sum of nn over all test cases does not exceed 2e5.
Output
For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from 1 to n in such a way as to maximize his result.
题目大意:
一个长度为n的数组a,将一个木块放在1-n任意的起始位置,木块可以向后移动并获得一定的分数。具体规则是:如果一个木块位于位置i,那么获得ai的分数,并移动到i+ai处,如此重复,直到某次i+ai > n,即木块移动出数组。现在已知长度n,和数组中每个元素ai,求所能获得分数的最大值。
题目分析:
假设一个木块在某次移动过程中,到达了位置i,那么它之后移动的路线及之后所能获得的得分只与位置i有关,而与它是如何移动到位置i无关。那么,我们只需要保证木块在到达位置i时已经获得了尽可能多的分数,当木块移动出数组时,获得的分数一定是较优的。
我们只需要维护一个数组b,记录木块移动至i位置时,最多获得bi的分数,那么数组b中的最大值即为我们所求的最后得分的最大值。
代码实现:
#include <bits/stdc++.h> using namespace std; const int maxn=2e5+5; typedef long long ll; int t; int n; int a[maxn]; ll b[maxn]; ll m; int main(){ scanf("%d",&t); while(t--){ m=0; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); b[i]=a[i]; } for(int i=1;i<=n;i++){ int pos=i+a[i]; if(pos<=n){ b[pos]=max(b[pos],b[i]+a[pos]); } m=max(m,b[i]); } printf("%lld\n",m); } return 0; }

浙公网安备 33010602011771号