CF797E Array Queries 题解
题意
给定一个大小为 \(n (1 \le n \le 10^5)\) 的数组 \(a\),其中任意元素不大于 \(n\)。
有 \(q\) 个询问,每个询问包含俩整数,\(p, k (1 \le p, k \le n)\),每次询问包含若干操作:将 \(p\) 变为 \(p + a_p + k\),求在本次询问中,需要多少次操作才能使得 \(p > n\)。
我模拟了十几分钟没看懂样例,结果发现题读错了。
- 原题面
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 + a__p + k. There operations are applied until p becomes greater than n. The answer to the query is the number of performed operations.
分析
首先想到朴素的方法就是对于每一个询问依次模拟,但是 \(10^5\) 的数据,显然会超时。可以发现到,询问是可以通过 DP 预处理的,在预处理之后,每次询问可以做到 \(O(n)\)。令 \(f[p][k]\) 表示询问为 \((p, k)\) 时的答案,则转移方程如下:
转移时 \(p\) 显然应当从大到小,因为 \(p + a_p + k\) 必然大于 \(p\),而 \(f[p][k]\) 可由 \(f[p + a_p + k][k]\) 转移而来。
说了半天还不是解决不了问题,你看 \(p,k\) 取值范围都多大了?
没错,纯 DP 确实解决不了问题,但是这正是本题的精妙之处。注意上面的公式 \(p = p + a_p + k\),按照这个式子,\(p\) 的每次操作都至少会增加 \(k\),那么 \(k\) 大了之后的增长会很快,因此如果 \(k\) 比较大的时候可以直接模拟,而 \(k\) 比较小的时候,则通过 DP 预处理,询问时直接输出答案即可。
我们将 \(k \le 300\) 的情况都给 DP 预处理出来,而大于 \(300\) 的部分则直接按公式模拟。结合题目所给出的数据范围,复杂度可以认为是 \(O(n \sqrt n)\),可以通过此题。
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, q;
int arr[maxn];
int f[maxn][305];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
}
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= 300; j++) {
if (i + arr[i] + j > n) f[i][j] = 1;
else f[i][j] = f[i + arr[i] + j][j] + 1;
}
}
scanf("%d", &q);
while (q--) {
int p, k;
int ans = 0;
scanf("%d%d", &p, &k);
if (k <= 300) {
printf("%d\n", f[p][k]);
continue;
}
while (p <= n) {
p = p + arr[p] + k;
ans++;
}
printf("%d\n", ans);
}
return 0;
}