CF797E Array Queries 题解

Problem - E - Codeforces

题意

给定一个大小为 n(1n105) 的数组 a,其中任意元素不大于 n
q 个询问,每个询问包含俩整数,p,k(1p,kn),每次询问包含若干操作:将 p 变为 p+ap+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.

分析

首先想到朴素的方法就是对于每一个询问依次模拟,但是 105 的数据,显然会超时。可以发现到,询问是可以通过 DP 预处理的,在预处理之后,每次询问可以做到 O(n)。令 f[p][k] 表示询问为 (p,k) 时的答案,则转移方程如下:

f[p][k]=1(p+ap+k>n)f[p][k]=f[p+ap+k][k]+1(p+ap+kn)

转移时 p 显然应当从大到小,因为 p+ap+k 必然大于 p,而 f[p][k] 可由 f[p+ap+k][k] 转移而来。

说了半天还不是解决不了问题,你看 p,k 取值范围都多大了?

没错,纯 DP 确实解决不了问题,但是这正是本题的精妙之处。注意上面的公式 p=p+ap+k,按照这个式子,p 的每次操作都至少会增加 k,那么 k 大了之后的增长会很快,因此如果 k 比较大的时候可以直接模拟,而 k 比较小的时候,则通过 DP 预处理,询问时直接输出答案即可。

我们将 k300 的情况都给 DP 预处理出来,而大于 300 的部分则直接按公式模拟。结合题目所给出的数据范围,复杂度可以认为是 O(nn),可以通过此题。

代码

#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;
}
posted @   jxyanglinus  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示