[codeforces797E]Array Queries

版权声明:辛辛苦苦码字,你们转载的时候记得告诉我 https://blog.csdn.net/dxyinme/article/details/90898124

time limit per test : 2 seconds
memory limit per test : 256 megabytes

a a is an array of n positive integers, all of which are not greater than n n .

You have to process q queries to this array. Each query is represented by two numbers p and k. Several operations are performed in each query; each operation changes p p to p + a p + k p + a_p + k . There operations are applied until p p becomes greater than n n . The answer to the query is the number of performed operations.

Input

The first line contains one integer n ( 1 n 100000 ) n (1 ≤ n ≤ 100000) .
The second line contains n n integers — elements of a ( 1 a i n a (1 ≤ ai ≤ n for each i i from 1 1 to n ) n) .
The third line containts one integer q ( 1 q 100000 ) q (1 ≤ q ≤ 100000) .
Then q q lines follow. Each line contains the values of p p and k k for corresponding query ( 1 p , k n ) (1 ≤ p, k ≤ n) .
Output

Print q q integers, ith integer must be equal to the answer to ith query.

Example
Input

3
1 1 1
3
1 1
2 1
3 1

Output

2
1
1

Note

Consider first example:
In first query after first operation p = 3, after second operation p = 5.
In next two queries p is greater than n after the first operation.

题意:
给一个数组a(a[i]<=n),长度为n(<=10w),q(<=10w)个询问,每次询问两个数字p,k,问最多能做几次操作
操作:p=p+a[p]+k(当p>n之后就不能做了)

题解:
对于 k &gt; n k&gt;\sqrt{n} 的情况,我们发现操作个数不会超过 n \sqrt{n} ,那就暴力即可
对于 k &lt; n k&lt;\sqrt{n} 的情况,我们用 n n n\sqrt{n} 的时间预处理出所有结果即可

#include<bits/stdc++.h>
#define LiangJiaJun main
using namespace std;
int f[404][100004];
int n,q,a[100004];
void ex(int k,int p){
    if(p>n)return ;
    if(f[k][p])return ;
    ex(k,p+k+a[p]);
    if(p+k+a[p]<=n)f[k][p]=f[k][p+k+a[p]]+1;
    else f[k][p]=1;
}
int bruteforce(int k,int p){
    int ans=0;
    while(p<=n){
        ++ans;
        p=p+k+a[p];
    }
    return ans;
}
int LiangJiaJun(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    memset(f,0,sizeof(f));
    for(int i=1;i<=sqrt(n);i++){
        for(int j=1;j<=n;j++){
            if(!f[i][j])ex(i,j);
        }
    }
    scanf("%d",&q);
    while(q--){
        int p,k;
        scanf("%d%d",&p,&k);
        if(k<=sqrt(n)){
            printf("%d\n",f[k][p]);
        }
        else{
            printf("%d\n",bruteforce(k,p));
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dxyinme/article/details/90898124