E. Array Queries
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
a is an array of n positive integers, all of which are not greater than 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 to p + ap + k. There operations are applied until p becomes greater than n. The answer to the query is the number of performed operations.
Input
The first line contains one integer n (1 ≤ n ≤ 100000).
The second line contains n integers — elements of a (1 ≤ ai ≤ n for each i from 1 to n).
The third line containts one integer q (1 ≤ q ≤ 100000).
Then q lines follow. Each line contains the values of p and k for corresponding query (1 ≤ p, k ≤ n).
Output
Print 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.
题意:题目比较简单自己看。
解题思路:我们先考虑一种暴力的做法,直接按他说的做,这样复杂度很高,但是我们可以发现,若是k很大,比如取350,那么每次询问最多n/350 == 434次,所以这是可以接受的,但是当k比较小的时候我们就不能接受了,于是我们在k比较小的时候考虑一种dp,我们令dp[i][j]表示在i位置,加上一个数j最后到结束时的最小操作数,我们由他的做法我们轻易的得到一个转移方程,如果i + a[i] + j > n,dp[i][j] = 1,反之dp[i][j] = dp[i + a[i] + j][j] + 1,这样就解决k比较小的情况,有人可能要问,能用dp解决,为什么不全部情况都用dp解决,只当k小时dp解决,当k大时暴力解决,若全部dp,需要100000*100000的数组,内存吃不消。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
const int size = 350;
int n,q;
int a[maxn];
int dp[maxn][size + 10];//对第i个元素进行操作,加上j最少需要的操作数
int main()
{
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
scanf("%d",&a[i]);
}
for(int j = 1; j <= size; j++)
{
for(int i = n; i >= 1; i--)
{
if(i + a[i] + j > n) dp[i][j] = 1;
else dp[i][j] = dp[i + a[i] + j][j] + 1;
}
}
scanf("%d",&q);
int p,k;
for(int i = 1; i <= q; i++)
{
scanf("%d%d",&p,&k);
if(k <= size) printf("%d\n",dp[p][k]);
else
{
int ans = 0;
while(p <= n)
{
ans++;
p += a[p] + k;
}
printf("%d\n",ans);
}
}
return 0;
}