跳到正文

题解

P13979 题解

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

文章信息

发布
2025年9月10日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 4 分钟
题目
P13979

版本

  1. v2当前
  2. v1

P13979 题解

以此题解纪念我自学了分块。

思路

既然是分块模板,那当然要用分块做啦。

分块

顾名思义,就是将一串信息切成一块一块的维护。

以这道题为例:

  1. 修改:
    • 如果我们发现 ll 和 rr 在同一个块,啥也不用说,直接暴力更改。
    • 如果不在同一块,这时我们可以暴力改前面和后面两段不完整的,再通过整体标记的方法改中间一些完整的块。
  2. 查询:
    • 同样的,如果 ll 和 rr 在同一块,暴力求和。
    • 否则,也可以通过暴力求两端不完整的的和,然后求中间完整的和。

设我们分了 xx 块,则单次时间复杂度最坏为 O(x+xn)O(x + \frac{x}{n})。很容易发现,当 x=nx = \sqrt{n} 时,最优。

不懂的请看代码。

Code

C++
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 3e5 + 1;

int n, op, l, r, id[N], len, siz[N];
// id 记录块的编号,siz 块的记录大小
ll c, a[N], tag[N], sum[N];
// a 记录题目数组,tag 是整体标记,sum 是块的和。

void Update(int l, int r, ll c){
    int idb = id[l], ide = id[r];
    if(idb == ide){
        for(int i = l; i <= r; ++i){
            a[i] += c, sum[id[i]] += c;
        }
        return;
    }
    for(int i = l; id[i] == idb; ++i){
        a[i] += c, sum[id[i]] += c;
    }
    for(int i = idb + 1; i < ide; ++i){
        tag[i] += c, sum[i] += c * siz[i];
    }
    for(int i = r; id[i] == ide; --i){
        a[i] += c, sum[id[i]] += c;
    }
}

int Query(int l, int r, ll c){
    int idb = id[l], ide = id[r];
    if(idb == ide){
        ll res = 0;
        for(int i = l; i <= r; ++i){
            res += a[i] + tag[id[i]];
        }
        return (res % c + c) % c;
    }
    ll res = 0;
    for(int i = l; id[i] == idb; ++i){
        res += a[i] + tag[id[i]];
    }
    for(int i = idb + 1; i < ide; ++i){
        res += sum[i];
    }
    for(int i = r; id[i] == ide; --i){
        res += a[i] + tag[id[i]];
    }
    return (res % c + c) % c;
}

int main(){
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n;
    len = sqrt(n);
    for(int i = 1; i <= n; ++i){
        cin >> a[i];
        id[i] = (i - 1) / len + 1;
        sum[id[i]] += a[i];
        siz[id[i]]++;
    }
    for(int i = 1; i <= n; ++i){
        cin >> op >> l >> r >> c;
        if(op == 0){
            Update(l, r, c);
        }else{
            cout << Query(l, r, c + 1) << '\n';
        }
    }
    return 0;
}