跳到正文

题解

题解:P17675 [IO 2025 #4] 骑士们的扩张

luogu_li4zi3约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月11日
收录
2026年10月12日
更新
2026年11月19日
篇幅
约 4 分钟
获赞
2
题目
P17675

版本

  1. v2当前
  2. v1

AC记录

题意

给你一个固定长度为 2×1052 \times 10^5 的数组 aa 以及 qq 次操作:

  1. 从 aa 的第一个元素开始,把 aa 分成若干个长度为 2k2k 的连续区间,对于每个区间,把它的前 kk 个位置加上 xx;
  2. 从 aa 的第一个元素开始,把 aa 分成若干个长度为 2k2k 的连续区间,对于每个区间,把它的前 kk 个位置减去 xx;
  3. 查询位置 tt 的值。

其中 q∈[1,4×105]q \in [1, 4 \times 10^5]。

思路

记 n=2×105n = 2 \times 10^5。

不难想到一个朴素的思路:修改时,直接用差分记录 n2k\dfrac{n}{2k} 个长度为 kk 的区间的修改,用树状数组维护差分数组的单点改和前缀和。

这种方法对于 kk 较大的修改有良好的表现,但对于 kk 较小的修改,几乎相当于暴力遍历整个数组,故我们要想办法避免用这种方法来应对较小 kk 的修改。

考虑根号分治:我们按照 kk 与 n\sqrt n 的大小关系把 kk 分为大 kk 与小 kk,大 kk 修改用树状数组,是 O(nlog⁡n)O(\sqrt n \log n) 的;小 kk 修改存入 sum 数组,kk 相同的修改累加,单次 O(1)O(1)。

查询时,枚举 sum 数组,对于每个 kk 检查 (t−1) mod 2k(t-1) \bmod 2k 是否小于 kk(即检查 tt 是否落在某个区间的前 kk 个位置中),若小于,则答案累加 sumksum_k,一共枚举 n\sqrt{n} 次,然后答案加上 query(t)(即大 kk 修改的贡献)就可以输出了。于是一次查询是 O(n+log⁡n)O(\sqrt{n}+\log n) 的。

这样的复杂度就基本可以接受了。

AC code

C++
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
const int B=450;
int lowbit(int x){
    return x&-x;
}
int n=2e5;
vector<int> c(2e5+10,0),sum(B+1,0);
void add(int l,int r,int v){
    for(int i=l;i<=n;i+=lowbit(i))c[i]+=v;
    for(int i=r+1;i<=n;i+=lowbit(i))c[i]-=v;
}
int query(int p){
    int res=0;
    for(int i=p;i>=1;i-=lowbit(i))res+=c[i];
    return res;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int q;cin>>q;
    while(q--){
        char op;
        cin>>op;
        if(op=='?'){
            int t;cin>>t;
            int ans=0;
            for(int i=1;i<=B;i++)
                if((t-1)%(2*i)<i)ans+=sum[i];
            ans+=query(t);
            cout<<ans<<'\n';
        }else{
            int x,k;cin>>x>>k;
            x*=(op=='+'?1:-1);
            if(k<=B)sum[k]+=x;
            else{
                for(int l=1;l<=n;l+=2*k){
                    int r=min(l+k-1,n);
                    add(l,r,x);
                }
            }
        }
    }
    return 0;
}