1. 程式人生 > 實用技巧 >【題解】Long Jumps 【水題】

【題解】Long Jumps 【水題】

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 arrayaofnelements and instructions for playing with it:

  • At first, choose indexi(1≤i≤n)— starting position in the array. Put the chip at the indexi (on the valueai).
  • Whilei≤n, addaiaito your score and move the chipaiaipositions to the right (i.e. replaceiwithi+ai).
  • Ifi>n, then Polycarp ends the game.

For example, ifn=5anda=[7,3,1,2,3], then the following game options are possible:

  • Polycarp choosesi=1. Game process:i=1⟶+78. The score of the game is:a1=7.
  • Polycarp choosesi=2. Game process:i=2⟶+35⟶+38. The score of the game is:a2+a5=6.
  • Polycarp choosesi=3. Game process:i=3⟶+14⟶+26. The score of the game is:a3+a4=3.
  • Polycarp choosesi=4. Game process:i=4⟶+26. The score of the game is:a4=2.
  • Polycarp choosesi=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 integert(1≤t≤1e4)— the number of test cases. Thentttest cases follow.

The first line of each test case contains one integern(1≤n≤2e5)— the length of the arrayaa.

The next line containsnnintegersa1,a2,…,an(1≤ai≤1e9)— elements of the arraya.

It is guaranteed that the sum ofnnover all test cases does not exceed2e5.

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 from1tonin 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;
}